Java Reference
In-Depth Information
}
}
}
}
});
thread.start();
}
public boolean stop() {
if (thread != null) {
if (thread.getState() == Thread.State.WAITING) {
synchronized (lock) {
flag = true;
lock.notifyAll();
}
return true;
}
}
return false;
}
}
Unfortunately,the
stop()
methodincorrectlyusesthe
Thread.getState()
methodto
check whether the thread is blocked and has not terminated before delivering the notific-
ation. Using the
Thread.getState()
method for synchronization control, such as check-
ing whether a thread is blocked on a wait, is inappropriate. Java Virtual Machines (JVMs)
are permitted to implement blocking using spin-waiting; consequently, a thread can be
blockedwithoutenteringthe
WAITING
or
TIMED_WAITING
state[Goetz2006].Becausethe
thread may never enter the
WAITING
state, the
stop()
method might fail to terminate the
thread.
If
doSomething()
and
stop()
are called from different threads, the
stop()
method
could fail to see the initialized
thread
, even though
doSomething()
was called earlier,
unlessthereisahappens-beforerelationshipbetweenthetwocalls.Ifthetwomethodsare
invoked by the same thread, they automatically have a happens-before relationship and
consequently cannot encounter this problem.
Compliant Solution
This compliant solution removes the check for determining whether the thread is in the
WAITING
state. This check is unnecessary because invoking
notifyAll()
affects only
threads that are blocked on an invocation of
wait()
: