Java Reference
In-Depth Information
Volatile variable rule.
A write to a volatile field happens-before every subsequent read of
that same field.
[4]
Thread start rule.
A call to Thread.start on a thread
happens-before
every action in the star-
ted thread.
Thread termination rule.
Any action in a thread
happens-before
any other thread detects
that
thread
has
terminated,
either
by
successfully
return
from
Thread.join
or
by
Thread.isAlive returning false.
Interruption rule.
A thread calling interrupt on another thread happens-before the interrup-
ted thread detects the interrupt (either by having InterruptedException thrown, or invoking
isInterrupted or interrupted).
Finalizer rule.
The end of a constructor for an object
happens-before
the start of the finalizer
for that object.
Transitivity. If A
happens-before
B, and B
happens-before
C, then A
happens-before C
.
Even though actions are only partially ordered, synchronization actions—lock acquisition
and release, and reads and writes of volatile variables—are totally ordered. This makes it
sensible to describe
happens-before
in terms of “subsequent” lock acquisitions and reads of
volatile variables.
Figure 16.2
.
illustrates the
happens-before
relation when two threads synchronize using a
common lock. All the actions within thread A are ordered by the program order rule, as are
the actions within thread B. Because A releases lock M and B subsequently acquires M, all
the actions in A before releasing the lock are therefore ordered before the actions in B after
acquiring the lock. When two threads synchronize on different locks, we can't say anything
about the ordering of actions between them—there is no
happens-before
relation between the
actions in the two threads.