Java Reference
In-Depth Information
One thread putting an object on a queue and another thread subsequently retrieving it consti-
tutes safe publication because there is guaranteed to be sufficient internal synchronization in
a BlockingQueue implementation to ensure that the enqueue happens-before the dequeue.
Other happens-before orderings guaranteed by the class library include:
Placing an item in a thread-safe collection happens-before another thread retrieves
that item from the collection;
Counting down on a CountDownLatch happens-before a thread returns from
await on that latch;
Releasing a permit to a Semaphore happens-before acquiring a permit from that
same Semaphore ;
Actions taken by the task represented by a Future happens-before another thread
successfully returns from Future.get ;
Submitting a Runnable or Callable to an Executor happens-before the task
begins execution; and
A thread arriving at a CyclicBarrier or Exchanger happens-before the other
threads are released from that same barrier or exchange point. If CyclicBarrier
uses a barrier action, arriving at the barrier happens-before the barrier action, which
in turn happens-before threads are released from the barrier.
16.2. Publication
Chapter 3 explored how an object could be safely or improperly published. The safe publica-
tion techniques described there derive their safety from guarantees provided by the JMM; the
risks of improper publication are consequences of the absence of a happens-before ordering
between publishing a shared object and accessing it from another thread.
16.2.1. Unsafe Publication
The possibility of reordering in the absence of a happens-before relationship explains why
publishing an object without adequate synchronization can allow another thread to see a par-
tially constructed object (see Section 3.5 ). Initializing a new object involves writing to vari-
ables—the new object's fields. Similarly, publishing a reference involves writing to another
Search WWH ::




Custom Search