Java Reference
In-Depth Information
When a timed lock attempt fails, you do not necessarily know why . Maybe there was a dead-
lock; maybe a thread erroneously entered an infinite loop while holding that lock; or maybe
some activity is just running a lot slower than you expected. Still, at least you have the op-
portunity to record that your attempt failed, log any useful information about what you were
trying to do, and restart the computation somewhat more gracefully than killing the entire
process.
Using timed lock acquisition to acquire multiple locks can be effective against deadlock even
when timed locking is not used consistently throughout the program. If a lock acquisition
times out, you can release the locks, back off and wait for a while, and try again, possibly
clearing the deadlock condition and allowing the program to recover. (This technique works
only when the two locks are acquired together; if multiple locks are acquired due to the nest-
ing of method calls, you cannot just release the outer lock, even if you know you hold it.)
10.2.2. Deadlock Analysis with Thread Dumps
While preventing deadlocks is mostly your problem, the JVM can help identify them when
they do happen using thread dumps . A thread dump includes a stack trace for each running
thread, similar to the stack trace that accompanies an exception. Thread dumps also include
locking information, such as which locks are held by each thread, in which stack frame they
were acquired, and which lock a blocked thread is waiting to acquire. [4] Before generating
a thread dump, the JVM searches the is-waiting-for graph for cycles to find deadlocks. If it
finds one, it includes deadlock information identifying which locks and threads are involved,
and where in the program the offending lock acquisitions are.
To trigger a thread dump, you can send the JVM process a SIGQUIT signal ( kill -3 ) on
Unix platforms, or press the Ctrl-\ key on Unix or Ctrl-Break on Windows platforms.
Many IDEs can request a thread dump as well.
If you are using the explicit Lock classes instead of intrinsic locking, Java 5.0 has no support
for associating Lock information with the thread dump; explicit Lock s do not show up at
all in thread dumps. Java 6 does include thread dump support and deadlock detection with
explicit Lock s, but the information on where Lock s are acquired is necessarily less precise
than for intrinsic locks. Intrinsic locks are associated with the stack frame in which they were
acquired; explicit Lock s are associated only with the acquiring thread.
Listing 10.7 shows portions of a thread dump taken from a production J2EE application. The
failure that caused the deadlock involves three components—a J2EE application, a J2EE con-
tainer, and a JDBC driver, each from different vendors. (The names have been changed to
Search WWH ::




Custom Search