Search code examples
javafinalhappens-before

Relationship between happens-before rules and initialization safety rule


I'm reading the Java Concurrency in Practice book.

When reading the chapter about JMM, it says:

The JMM defines a partial ordering called happens-before on all actions within the program. To guarantee that the thread executing action B can see the results of action A (whether or not A and B occur in different threads), there must be a happens-before relationship between A and B.

However, I can't use any happens-before rule to derive the "Initialization safety" rule:

Initialization safety guarantees that for properly constructed objects, all threads will see the correct values of final fields that were set by the constructor, regardless of how the object is published.

Can we use happens-before rules to derive the "Initialization safety" rule, or are these two concepts just same level abstraction?


Solution

  • The “Initialization safety rule” is a special rule which can not be derived from the other happens-before relationships and can not get combined with other happens-before relationships to derive more rules.

    The rule is specified in JLS §17.5, final Field Semantics:

    final fields also allow programmers to implement thread-safe immutable objects without synchronization. A thread-safe immutable object is seen as immutable by all threads, even if a data race is used to pass references to the immutable object between threads. This can provide safety guarantees against misuse of an immutable class by incorrect or malicious code. final fields must be used correctly to provide a guarantee of immutability.

    The chapter is too long to cite it completely, but I want to emphasize this specific statement:

    This happens-before ordering does not transitively close with other happens-before orderings.

    So the “Initialization safety rule” exists in addition to the other happens-before relationships, to aid the construction of immutable objects.