Java Reference
In-Depth Information
Placing an element on a BlockingQueue or a ConcurrentLinkedQueue
safely publishes it to any thread that retrieves it from the queue.
Other handoff mechanisms in the class library (such as Future and Exchanger ) also con-
stitute safe publication; we will identify these as providing safe publication as they are intro-
duced.
Using a static initializer is often the easiest and safest way to publish objects that can be stat-
ically constructed:
public static Holder holder = new Holder(42);
Static initializers are executed by the JVM at class initialization time; because of internal
synchronization in the JVM, this mechanism is guaranteed to safely publish any objects ini-
tialized in this way [JLS 12.4.2].
3.5.4. Effectively Immutable Objects
Safe publication is sufficient for other threads to safely access objects that are not going to be
modified after publication without additional synchronization. The safe publication mechan-
isms all guarantee that the as-published state of an object is visible to all accessing threads as
soon as the reference to it is visible, and if that state is not going to be changed again, this is
sufficient to ensure that any access is safe.
Objects that are not technically immutable, but whose state will not be modified after pub-
lication, are called effectively immutable . They do not need to meet the strict definition of
immutability in Section 3.4 ; they merely need to be treated by the program as if they were
immutable after they are published. Using effectively immutable objects can simplify devel-
opment and improve performance by reducing the need for synchronization.
Safely published effectively immutable objects can be used safely by any thread without ad-
ditional synchronization.
Search WWH ::




Custom Search