Java Reference
In-Depth Information
Ask the Expert
Q :
I have heard the term deadlock applied to misbehaving multithreaded pro-
grams. What is it, and how can I avoid it? Also, what is a race condition , and
how can I avoid that, too?
A : Deadlock is, as the name implies, a situation in which one thread is waiting for an-
other thread to do something, but that other thread is waiting on the first. Thus, both
threads are suspended, waiting on each other, and neither executes. This situation is
analogous to two overly polite people, both insisting that the other step through a
door first!
Avoiding deadlock seems easy, but it's not. For example, deadlock can occur in round-
about ways. The cause of the deadlock often is not readily understood just by looking at
the source code to the program because concurrently executing threads can interact in
complex ways at run time. To avoid deadlock, careful programming and thorough testing
is required. Remember, if a multithreaded program occasionally “hangs,” deadlock is the
likely cause.
A race condition occurs when two (or more) threads attempt to access a shared resource
at the same time, without proper synchronization. For example, one thread may be writing
a new value to a variable while another thread is incrementing the variable's current value.
Without synchronization, the new value of the variable will depend upon the order in
which the threads execute. (Does the second thread increment the original value or the
new value written by the first thread?) In situations like this, the two threads are said to be
“racing each other,” with the final outcome determined by which thread finishes first. Like
deadlock, a race condition can occur in difficult-to-discover ways. The solution is preven-
tion: careful programming that properly synchronizes access to shared resources.
Suspending, Resuming, and Stopping Threads
It is sometimes useful to suspend execution of a thread. For example, a separate thread can
be used to display the time of day. If the user does not desire a clock, then its thread can be
suspended. Whatever the case, it is a simple matter to suspend a thread. Once suspended, it
is also a simple matter to restart the thread.
The mechanisms to suspend, stop, and resume threads differ between early versions of
Java and more modern versions, beginning with Java 2. Prior to Java 2, a program used
Search WWH ::




Custom Search