“This is the 27th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

The vast sea of millions, thank you for this second you see here. I hope my article is helpful to you!

May you keep your love and go to the mountains and seas in the coming days!

Note: As for the final keyword, it is also a keyword we often use. It can be modified on a class, or on a variable, or on a method to define some of its immutability!

The String class, for example, is final, and its character array is final. But have you really understood some details of the final?

Start with this article and take you deep into the details of final!

👋 Learn about final from the in-memory model

👩🦼final Domain reorder rule

For the JMM memory model, there are two reordering rules for final fields:

  1. Write: Writes to a final field within a constructor, and then assigns a reference to the constructor to a reference variable. Operations cannot be reordered.

  2. Read: The first reading of a reference to an object containing a final field and the subsequent first writing of the final field cannot be reordered.

Specific we according to the code demo side to explain:

Code:

package com.nz.test;

/** * Tests the JMM memory model's rules for reordering final fields */
public class JMMFinalTest {

    // Common variables
    private int variable;
    / / final variables
    private final int variable2;
    private static JMMFinalTest jmmFinalTest;

    // In the constructor, write normal and final variables
    public JMMFinalTest(a){
        variable = 1;  // 1. Write common variables
        variable2 = 2; // 2. Write final variables
    }

    // Imitate A write operation --> assume thread A to write
    public static void write(a) {
        // new current class object --> and completes the assignment in the constructor
        jmmFinalTest = new JMMFinalTest();
    }

    // Simulate a read operation --> assume thread B does the read operation
    public static void read(a) {
        // Read operation:
        JMMFinalTest test = jmmFinalTest; // 3. Read a reference to the object
        int localVariable = test.variable;
        intlocalVariable2 = test.variable2; }}Copy the code

Write the final field reorder

Write final field reorder Rules write to a final field within a constructor and then assign a reference to the constructor to a reference variable. Operations cannot be reordered. This rule forbids initializations of final fields that must be inside the constructor and cannot be reordered outside the constructor. Implementation of this rule has two main aspects:

  1. The JMM memory model disallows the compiler tofinalThe write of the domain is reordered outside the constructor;
  2. The compiler will be infinalInsert one before the field is written and the constructor return returnsstorestoreMemory barriers. This memory barrier can disable the processorfinalThe write of the field is reordered outside the constructor.

Let’s look at the write method again. Although it’s only one line of code, it actually has three steps:

  1. Apply for a block of memory in the JVM heap
  2. Object to initialize
  3. Assigns the reference address of the memory space in the heap to a reference variable, jmmFinalTest.

For the normal variable, its initialization can be reordered out of the constructor, i.e. the steps that were 1-2-3 May now result in 1-3-2 after the constructor returns!

In the case of the final variable variable2, its initialization must be within the constructor, 1-2-3.

Let’s look at a possible scenario:

As for the visibility of variables, because the common variable variable may have a phenomenon of reordering, the value read may be different, may be 0 or 1. But the final variable variable2, which must read 2, has a StoreStore memory barrier that guarantees reordering operations with the following operations.

Thus, the reordering rules that write final fields guarantee that the object’s final fields are properly initialized before the reference is visible to any thread, whereas normal fields do not.

Read the final field reordering rules

Reading a reference to an object containing a final field for the first time and then writing the final field for the first time cannot be reordered. How do you do that?

It actually inserts a LoadLoad memory barrier before a final field operation is read.

Looking at the read method, it actually has three steps:

  1. First read reference variable jmmFinalTest;
  2. First read the common domain variable variable that references jmmFinalTest;
  3. First read that references the variable jmmFinalTestfinalThe domain variables variable2.

We take the normal order of write operations, for read cases can occur diagram:

The common domain variable variable of the read object may be reordered before the reference of the read object. In this case, thread B will read the common domain variable of the read object before it has read the reference of the read object, which is obviously a wrong operation.

A read to a final field ensures that a reference to the object is read before a final field variable is read, thereby avoiding this problem.

Thus, reordering for reading a final field ensures that the reference to the object containing the final field of an object is read before reading the final field of an object, whereas normal fields do not have this guarantee.

🌸 summary

Believe everybody the reader that a keyword for final had certain understanding, actually additional expand own aspect of knowledge is quite necessary, otherwise people ask you, would you speechless, and once you after in-depth knowledge, every day you in the future articles will gush, shinning!!!!! Right? We still have a handful of things to explore and explore! Let’s continue to look forward to the final content of the next chapter. Welcome to the next chapter!

Let’s refuel together, too! I am not just, if there is any missing, wrong place, also welcome you to criticize in the comments of talent leaders! Of course, if this article is sure to help you a little, please kindly and lovely talent leaders to give a thumb-up, favorites, one key three even, thank you very much!

Here, the world is closed for today, good night! Although this article is over, I am still here, never finished. I will try to keep writing articles. The coming days are long, why fear the car yao ma slow!

Thank you all for seeing this! May you live up to your youth and have no regrets!