final fields freeze semantics in threads

45 Views Asked by At

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
        }
    }
}

If the constructor is changed to:

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

According to happens-before order: hb(y=4, x=3), according to final field freeze: hb(x=3, f=new FinalFieldExample()).

So, is hb(y=4, f = new FinalFieldExample()) correct? Is f.y in reader() guaranteed to see 4?

0

There are 0 best solutions below