What is the exact value of the final safe context field in JLS

The term final-field context is often used in paragraph 17.5.3 of the JLS (subsequent modification of finite fields). Although, as you can understand from the 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 depends on the implementation; there is still no clear definition of the term.
Can I assume that if we have a freezing F of the final field (which occurs at the end of the construction of the object or the final field specified by the reflection API) and action A such that occurs before (F, A), then A is in safe for the final field context?

+6
source share
1 answer

To understand what JLS 17.5.3 means "safe end-field context", consider the following code

 public static final AccountType SINGLETON_ACCOUNT_TYPE = new AwesomeAccountType(); 

Prior to Java 5, Java had a “feature” where developers were sure that thread safety for building AwesomeAccountType and its purpose for SINGLETON_ACCOUNT_TYPE was undertaken. Unfortunately, the specification was ambiguous and / or did not indicate behavior that led to different JVM implementations having different behavior. As a result, this script was unsafe and portable in Java.

The reason for this was that the order of operations involved in constructing AwesomeAccountType could be reordered at runtime so that the reference to the object could be visible to another thread before the object was completely constructed. The behavior was non-deterministic, it always worked on single-core processors and usually worked on Intel processors, but was in a hurry on processors with a weaker memory model such as Dec Alpha.

“End field context” is the area of ​​code that participates in the assignment to the above end field (SINGLETON_ACCOUNT_TYPE) and covers the entire constructor for AwesomeAccountType AND the code internal to the JVM to allocate and initialize memory for the object.

These changes to the Java memory model were made in JSR133, the following FAQ is very useful for understanding the context of the changes made: JSR133 FAQ .

+5
source

Source: https://habr.com/ru/post/975018/


All Articles