Java Reference
In-Depth Information
Example 4−2: ThreadLister.java (continued)
// Create a simple Swing GUI
JFrame frame = new JFrame("ThreadLister Demo");
JTextArea textarea = new JTextArea();
frame.getContentPane().add(new JScrollPane(textarea),
BorderLayout.CENTER);
frame.setSize(500, 400);
frame.setVisible(true);
// Get the threadlisting as a string using a StringWriter stream
StringWriter sout = new StringWriter(); // To capture the listing
PrintWriter out = new PrintWriter(sout);
ThreadLister.listAllThreads(out);
// List threads to stream
out.close();
String threadListing = sout.toString(); // Get listing as a string
// Finally, display the thread listing in the GUI
textarea.setText(threadListing);
}
}
Deadlock
Multithreaded programming requires a programmer to take special care in several
areas. For example, if multiple threads can be changing the state of an object at
the same time, you must typically use synchronized methods or the synchronized
statement to ensure that only one thread changes the object's state at a time. If you
do not, two threads could end up overwriting each other's edits, leaving the object
in an inconsistent state.
Unfortunately, using synchronization can itself cause problems. Thread synchro-
nization involves acquiring an exclusive lock. Only the one thread that currently
holds the lock can execute the synchronized code. When a program uses more
than one lock, however, a situation known as deadlock can arise. Deadlock occurs
when two or more threads are all waiting to acquire a lock that is currently held
by one of the other waiting threads. Because each thread is waiting to acquire a
lock, none ever releases the lock or locks it already holds, which means that none
of the waiting threads ever acquires the lock it is waiting for. The situation is a
total impasse; all the threads involved come to a halt, and the program can't con-
tinue.
Example 4-3 is a simple program that creates a deadlock situation in which two
threads attempt to acquire locks on two different resources. It is pretty easy to see
how deadlock can arise in this simple program. It might not be as clear, however,
if there were synchronized methods involved, instead of a simple symmetrical set
of synchronized statements. More complicated situations also arise with multiple
threads and multiple resources. In general, the problem of deadlock is a deep and
nasty one. One good technique for preventing it, however, is for all threads always
to acquire all the locks they need in the same order.
Search WWH ::




Custom Search