Java Reference
In-Depth Information
its body is not executed until the lock action has successfully completed. If the method is an
instance method, it locks the monitor associated with the instance for which it was invoked
(that is, the object that will be known as
this
during execution of the body of the method). If
the method is
static
, it locks the monitor associated with the
Class
object that represents the
class in which the method is defined. If execution of the method's body is ever completed,
either normally or abruptly, an unlock action is automatically performed on that same mon-
itor.
The Java programming language neither prevents nor requires detection of deadlock condi-
tions. Programs where threads hold (directly or indirectly) locks on multiple objects should
use conventional techniques for deadlock avoidance, creating higher-level locking primit-
ives that do not deadlock, if necessary.
Other mechanisms, such as reads and writes of
volatile
variables and the use of classes in
the
java.util.concurrent
package, provide alternative ways of synchronization.
17.2. Wait Sets and Notification
Every object, in addition to having an associated monitor, has an associated
wait set
. A wait
set is a set of threads.
When an object is first created, its wait set is empty. Elementary actions that add threads to
and remove threads from wait sets are atomic. Wait sets are manipulated solely through the
methods
Object.wait
,
Object.notify
, and
Object.notifyAll
.
Wait set manipulations can also be affected by the interruption status of a thread, and by
the
Thread
class's methods dealing with interruption. Additionally, the
Thread
class's meth-
ods for sleeping and joining other threads have properties derived from those of wait and
notification actions.
17.2.1. Wait
Wait actions
occur upon invocation of
wait()
, or the timed forms
wait(long millisecs)
and
wait(long millisecs, int nanosecs)
.
A call of
wait(long millisecs)
with a parameter of zero, or a call of
wait(long millisecs, int
nanosecs)
with two zero parameters, is equivalent to an invocation of
wait()
.
A thread
returns normally
from a wait if it returns without throwing an
InterruptedException
.