Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 5 ■ CONTROL FLOW, LOOPING, AND BRANCHING

Code to connect to a server in a real-world application also checks for a number of exceptions and
does not print to the console but rather updates a status window (that includes a cancel button) for the
user.
Notice the break statement. If we do connect, we don't want to wait for the rest of the code to run
(especially because it contains a sleep instruction). Consequently, we jump out of the while loop after we
connect. The handy thing is that, if we connect on the first try, we never wait and never loop. We shoot
through the code as though it were linear (except for the overhead of the comparison in the while) and
we're done. If we usually do connect on the first try, that's a nice little optimization. We cover break
statements in detail later in this chapter.
Notice also the try-catch block and the call to Thread.sleep(2000) within it. The Thread.sleep()
method tells the current thread to sleep for some number of milliseconds, letting other processes run. In
other words, it lets other processes get some work done while your process takes a break. If it weren't
present, the JVM wouldn't try to do anything else until your while loop exited. That's generally a bad
practice, because it can bring an entire application to a halt while everything waits for your code. Exactly
how long to let your thread sleep varies by a number of factors (how long what you're doing takes, how
important what you're doing is, and so on).


■ Tip You should almost always put the current thread to sleep for a bit to let other processes work when you


do anything that has to be timed.


Do-while Loops


Do-while loops work much like while loops. The difference is that checking the condition comes after
the block of code runs. Put differently, the test comes at the bottom of the loop rather than at the top.
That means the code always runs at least once. Because we always want our mail server connector to try
at least once, it's a great case for converting to a do-while loop (see Listing 5-15).


Listing 5-15. Do-while loop


boolean connected = false;
long now = System.currentTimeMillis();
long oneMinuteFromStart = System.currentTimeMillis() + 60000;
do {
System.out.println("Trying to connect....");
if (MailServer.connect()) {
connected = true;
break;
}
// pause for two seconds
// to let other processes work, too
try {
System.out.println("(letting other processes run)");
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}

Free download pdf