Safe publication
Could not understand methods 1 and 3 as to how it helps to achieve safe publication. Can anyone help me understand this with an example if possible.
To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:
Initializing an object reference from a static initializer
Storing a reference to it into a volatile field or AtomicReference
Storing a reference t开发者_StackOverflowo it into a final field of a properly constructed object
Storing a reference to it into a field that is properly guarded by a
lock.
There are specific synchronization rules in the Java memory model that define the "happens-before" relationships in a Java program that determine when an application is guaranteed to see "fresh" values of the variables it references. The "safe publication" methods achieve safe publication as a logical consequence of the synchronization rules, and other rules set out in the Java Language Specification.
JLS section 12.4.2 specifies the procedure by which classes are initialized. The synchronization that occurs in this procedure is presumably sufficient to guarantee safe publication.
JLS section 17.4. bullet point 2 deals with volatile fields. This property of AtomicReferences is a consequence of the behaviour specified in the javadocs.
JLS section 17.5.
JLS section 17.4. bullet point 1
To really understand this stuff, you need to read all of JLS section 17, carefully, a number of times.
精彩评论