I came across a deadlock scenario which can be summarized as the StaticDeadlock class shown below.
This simple program will freeze at o.getClass(). Here\'s
Yes, that's pretty much it. The new thread is waiting for the class initializer of StaticDeadlock
to complete before it accesses the static member. See section 12.4.2 of the Java Language Specification for more details, in particular these steps:
Synchronize (§14.19) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.1).
If initialization is in progress for the class or interface by some other thread, then wait on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.
If initialization is in progress for the class or interface by the current thread, then this must be a recursive request for initialization. Release the lock on the Class object and complete normally.
If the class or interface has already been initialized, then no further action is required. Release the lock on the Class object and complete normally.
It won't even get past step 1 in the second thread, as the first thread has the lock and won't release it.
Note that it's not calling getClass()
which causes the problem - doing anything which requires the value of o
will make the second thread wait until the class initializer has completed, which of course won't happen because the first thread is waiting for the second thread to finish.