Final Fields Semantics in Threads

2019-03-28 11:52发布

问题:

This is from JLS 17.5:

The usage model for final fields is a simple one. Set the final fields for an object in that object's constructor. Do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.

The discussion in JLS 17.5 includes this sample code:

class FinalFieldExample {
    final int x;
    int y;
    static FinalFieldExample f;

    public FinalFieldExample() {
        x = 3;
        y = 4;
    }

    static void writer() {
        f = new FinalFieldExample();
    }

    static void reader() {
        if (f != null) {
            int i = f.x; // guaranteed to see 3
            int j = f.y; // could see 0
        }
    }
}

I tried reusing this code to replicate the situation above, and here is what I have:

public class FinalFieldThread extends Thread {

    public static void main(String[] args) {
        ThreadA threadA = new ThreadA();
        ThreadB threadB = new ThreadB();

        threadB.start();
        threadA.start();
        //threadB.start();

    }
}

class ThreadA extends Thread {

    @Override
    public void run() {
        System.out.println("ThreadA");
        FinalFieldExample.writer();
    }
}

class ThreadB extends Thread {

    @Override
    public void run() {
        System.out.println("ThreadB");
        FinalFieldExample.reader();
    }
}

I can test how final gets read correctly, but how can I replicate when it is not read correctly (i.e. when there is a reference to the tread before the constructor is finished?)

回答1:

What you are looking for

What you are trying to test is called Don't publish the "this" reference during construction or Visibility Hazard. Read the following links in the order they are provided.

Reading

  1. Java theory and practice: Safe construction techniques
  2. JSR 133 (Java Memory Model) FAQ
  3. Do the ‘up to date’ guarantees for values of Java's final fields extend to indirect references?

Sample Code

class FinalField
{
    final int x;
    int y;

    public FinalField()
    {
        Thread t = new Thread(new TestThread(this));
        t.start();

        y = 4;
        x = 3;
    }
}

class TestThread implements Runnable
{
    FinalField f;
    TestThread(FinalField f)
    {
        if(f.x != 3)
            System.out.println("value of x = " + f.x);

        this.f = f;
    }

    public void run() 
    {
        if(f.x != 3)
            System.out.println("value of x = " + f.x);
    }
}

public class Test
{
    public static void main(String[] args) 
    {
        for(int i=0; i<100; i++)
        {
            new FinalField();
        }
    }
}

Output

value of x = 0
value of x = 0
value of x = 0
.
.
.
value of x = 0
value of x = 0
value of x = 0

Explanation of the output

When I access the final field in the constructor of my thread then at that time the final field x was not properly initialized, and that's why we are getting 0. Whereas when I access the same field in the run() then by that time the final field x is initialized to 3. This is happening because of the escaping of the reference to the object of FinalField. Read the 1st link I have shared, it is much more detailed.