Compared with the locks and volatile introduced earlier, reading and writing the final field are more like ordinary variable access. For final fields, the compiler and processor must abide by two reordering rules:
Writing a final field within the constructor and subsequently assigning a reference to the constructed object to a reference variable. These two Operations cannot be reordered.
The first read of a reference to an object containing a final field and the subsequent first read of the final field cannot be reordered between the two operations.
Below, we use some example code to illustrate these two rules respectively:
public class FinalExample { int i; //普通变量 final int j; //final变量 static FinalExample obj; public void FinalExample () { //构造函数 i = 1; //写普通域 j = 2; //写final域 } public static void writer () { //写线程A执行 obj = new FinalExample (); } public static void reader () { //读线程B执行 FinalExample object = obj; //读对象引用 int a = object.i; //读普通域 int b = object.j; //读final域 } }
It is assumed that one thread A executes the writer () method, and then another thread B executes the reader () method. Below we illustrate these two rules through the interaction of these two threads.
Reordering rules for writing final fields
The reordering rules for writing final fields prohibit reordering the writing of final fields outside the constructor. The implementation of this rule includes the following two aspects:
JMM prohibits the compiler from reordering the writes of the final field outside the constructor.
The compiler will insert a StoreStore barrier after writing the final field and before the constructor return. This barrier prevents the processor from reordering writes to final fields outside the constructor.
Now let us analyze the writer () method. The writer () method contains only one line of code: finalExample = new FinalExample (). This line of code contains two steps:
Construct an object of type FinalExample;
Assign the reference of this object to the reference variable obj.
Assuming that there is no reordering between thread B reading the object reference and reading the object's member fields (I will explain why this assumption is needed soon), the following figure is a possible execution sequence:
In the above figure, the operation of writing to the ordinary field was reordered by the compiler outside the constructor, and the reading thread B mistakenly read the value of the ordinary variable i before it was initialized. The operation of writing the final field is "limited" within the constructor by the reordering rules for writing the final field, and the reading thread B correctly reads the value of the final variable after initialization.
Writing the reordering rules of the final field can ensure that the object's final field has been correctly initialized before the object reference is visible to any thread, while ordinary fields do not have this guarantee. Taking the above figure as an example, when the reading thread B "sees" the object reference obj, it is likely that the obj object has not been constructed yet (the write operation to the ordinary field i is reordered outside the constructor, and the initial value 2 has not been written yet) Common domain i).
Reordering rules for reading final fields
The reordering rules for reading final fields are as follows:
In a thread, the first time reading an object reference is the same as the first time reading the final field contained in the object. JMM prohibits the processor from reordering these two operations (note that this rule applies only to the processor). The compiler inserts a LoadLoad barrier before the final field read operation.
There is an indirect dependency between the first reading of the object reference and the first reading of the final field contained in the object. Since the compiler respects indirect dependencies, the compiler does not reorder these two operations. Most processors will also honor indirect dependencies, and most processors will not reorder these two operations. However, a few processors allow reordering operations with indirect dependencies (such as alpha processors), and this rule is specifically designed for such processors.
The reader() method includes three operations:
The initial reading reference variable obj;
The initial reading reference variable obj points to the ordinary domain j of the object.
The initial read reference variable obj points to the final field i of the object.
Now we assume that no reordering occurs in writing thread A, and the program is executed on a processor that does not comply with indirect dependencies. The following is a possible execution sequence:
In the above figure, the operation of reading the ordinary field of the object is reordered by the processor before reading the object reference. When reading a common field, the field has not been written by writing thread A. This is an incorrect read operation. The reordering rules for reading the final field will "limit" the operation of reading the object's final field to after reading the object reference. At this time, the final field has been initialized by the A thread, which is a correct read operation.
The reordering rules for reading final fields ensure that before reading the final field of an object, the reference to the object containing the final field must be read first. In this example program, if the reference is not null, then the final field of the referenced object must have been initialized by thread A.
If the final field is a reference type
The final field we saw above is the basic data type. Let us see what the effect will be if the final field is a reference type?
Please see the following sample code:
public class FinalReferenceExample { final int[] intArray; //final是引用类型 static FinalReferenceExample obj; public FinalReferenceExample () { //构造函数 intArray = new int[1]; //1 intArray[0] = 1; //2 } public static void writerOne () { //写线程A执行 obj = new FinalReferenceExample (); //3 } public static void writerTwo () { //写线程B执行 obj.intArray[0] = 2; //4 } public static void reader () { //读线程C执行 if (obj != null) { //5 int temp1 = obj.intArray[0]; //6 } } }
这里final域为一个引用类型,它引用一个int型的数组对象。对于引用类型,写final域的重排序规则对编译器和处理器增加了如下约束:
在构造函数内对一个final引用的对象的成员域的写入,与随后在构造函数外把这个被构造对象的引用赋值给一个引用变量,这两个操作之间不能重排序。
对上面的示例程序,我们假设首先线程A执行writerOne()方法,执行完后线程B执行writerTwo()方法,执行完后线程C执行reader ()方法。下面是一种可能的线程执行时序:
在上图中,1是对final域的写入,2是对这个final域引用的对象的成员域的写入,3是把被构造的对象的引用赋值给某个引用变量。这里除了前面提到的1不能和3重排序外,2和3也不能重排序。
JMM可以确保读线程C至少能看到写线程A在构造函数中对final引用对象的成员域的写入。即C至少能看到数组下标0的值为1。而写线程B对数组元素的写入,读线程C可能看的到,也可能看不到。JMM不保证线程B的写入对读线程C可见,因为写线程B和读线程C之间存在数据竞争,此时的执行结果不可预知。
如果想要确保读线程C看到写线程B对数组元素的写入,写线程B和读线程C之间需要使用同步原语(lock或volatile)来确保内存可见性。
为什么final引用不能从构造函数内“逸出”
前面我们提到过,写final域的重排序规则可以确保:在引用变量为任意线程可见之前,该引用变量指向的对象的final域已经在构造函数中被正确初始化过了。其实要得到这个效果,还需要一个保证:在构造函数内部,不能让这个被构造对象的引用为其他线程可见,也就是对象引用不能在构造函数中“逸出”。为了说明问题,让我们来看下面示例代码:
public class FinalReferenceEscapeExample { final int i; static FinalReferenceEscapeExample obj; public FinalReferenceEscapeExample () { i = 1; //1写final域 obj = this; //2 this引用在此“逸出” } public static void writer() { new FinalReferenceEscapeExample (); } public static void reader { if (obj != null) { //3 int temp = obj.i; //4 } } }
假设一个线程A执行writer()方法,另一个线程B执行reader()方法。这里的操作2使得对象还未完成构造前就为线程B可见。即使这里的操作2是构造函数的最后一步,且即使在程序中操作2排在操作1后面,执行read()方法的线程仍然可能无法看到final域被初始化后的值,因为这里的操作1和操作2之间可能被重排序。实际的执行时序可能如下图所示:
从上图我们可以看出:在构造函数返回前,被构造对象的引用不能为其他线程可见,因为此时的final域可能还没有被初始化。在构造函数返回后,任意线程都将保证能看到final域正确初始化之后的值。
final语义在处理器中的实现
现在我们以x86处理器为例,说明final语义在处理器中的具体实现。
上面我们提到,写final域的重排序规则会要求译编器在final域的写之后,构造函数return之前,插入一个StoreStore障屏。读final域的重排序规则要求编译器在读final域的操作前面插入一个LoadLoad屏障。
由于x86处理器不会对写-写操作做重排序,所以在x86处理器中,写final域需要的StoreStore障屏会被省略掉。同样,由于x86处理器不会对存在间接依赖关系的操作做重排序,所以在x86处理器中,读final域需要的LoadLoad屏障也会被省略掉。也就是说在x86处理器中,final域的读/写不会插入任何内存屏障!
JSR-133为什么要增强final的语义
在旧的Java内存模型中 ,最严重的一个缺陷就是线程可能看到final域的值会改变。比如,一个线程当前看到一个整形final域的值为0(还未初始化之前的默认值),过一段时间之后这个线程再去读这个final域的值时,却发现值变为了1(被某个线程初始化之后的值)。最常见的例子就是在旧的Java内存模型中,String的值可能会改变(参考文献2中有一个具体的例子,感兴趣的读者可以自行参考,这里就不赘述了)。
为了修补这个漏洞,JSR-133专家组增强了final的语义。通过为final域增加写和读重排序规则,可以为java程序员提供初始化安全保证:只要对象是正确构造的(被构造对象的引用在构造函数中没有“逸出”),那么不需要使用同步(指lock和volatile的使用),就可以保证任意线程都能看到这个final域在构造函数中被初始化之后的值。
以上就是Java内存模型深度解析:final的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!