Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the exact meaning of final-field-safe context in JLS

Tags:

java

final

jls

Term final-field-safe context is used frequently in paragraph 17.5.3 of JLS (subsequent modification of final fields). Although, as could be understood from specification (if I'm wrong here, please correct me)

An implementation may provide a way to execute a block of code
in a final-fieldsafe context.

the exact behavior is implementation-dependent, there is still no clear definition of term.
Could I suppose, that if we have a final-field freeze F (one that occurs at the end of object construction or final-field set by the means of reflection API) and an action A, such that happens-before(F, A), then A is in final-field-safe context?

like image 968
mkrakhin Avatar asked Sep 09 '14 08:09

mkrakhin


1 Answers

To help understand what JLS 17.5.3 means by a 'final-field safe context', consider the following code

public static final AccountType SINGLETON_ACCOUNT_TYPE = new AwesomeAccountType();

Before Java 5, Java had a 'feature' where the thread safety of the construction of AwesomeAccountType and its assignment to SINGLETON_ACCOUNT_TYPE was taken by developers to be safe. Unfortunately the spec was ambiguous and/or did not state the behavior, which lead to different JVM implementations having different behaviors. The result was that Java was often not thread safe and portable in this scenario.

The reason for this was that the order of the operations involved in constructing of AwesomeAccountType could get reordered at runtime in such a way that the reference to the object could become visible to another thread before the object was fully constructed. The behavior was non-deterministic, it always worked on single core CPUs and usually worked on intel CPUs but would fall over in a hurry on CPUs with a weaker memory model such as the Dec Alpha.

A 'final-field safe context' then is the region of code that is involved in the assignment to the above final field (SINGLETON_ACCOUNT_TYPE), and it covers all of the constructor for AwesomeAccountType AND the code internal to the JVM for allocating and initializing the memory for the object.

These changes to the Java Memory Model were made under JSR133, the following FAQ is very useful for understanding the context of the changes that were made: JSR133 FAQ.

like image 52
Chris K Avatar answered Nov 03 '22 21:11

Chris K