Java Reference
In-Depth Information
it is appropriate to subclass
Thread
explicitly instead of using a
Runnable
in a pool: in
order to test proper termination with
join
. The same approach can be used to test that the
taker thread unblocks after an element is placed in the queue by the main thread.
It is tempting to use
Thread.getState
to verify that the thread is actually blocked on
a condition wait, but this approach is not reliable. There is nothing that requires a blocked
thread
ever
to enter the
WAITING
or
TIMED_WAITING
states, since the JVM can choose
to implement blocking by spin-waiting instead. Similarly, because spurious wakeups from
WAITING
or
TIMED_WAITING
state may temporarily transition to
RUNNABLE
even if the
condition for which it is waiting is not yet true. Even ignoring these implementation op-
tions, it may take some time for the target thread to settle into a blocking state.
The result of
Thread.getState should not be used for concurrency control, and is of limited usefulness for
testing—its primary utility is as a source of debugging information.
Listing 12.3. Testing Blocking and Responsiveness to Interruption.