JavaMemoryModel: non-finals with synchronized getters

From: Joseph Bowbeer (jozart@csi.com)
Date: Sat Mar 31 2001 - 21:04:31 EST


A couple questions about final:

Consider the following class, where the field 'x' is not final, but where
the getX method is synchronized:

    class Foo {
        private int x;
        Foo() { x = 1; }
        synchronized int getX() { return x; }
    }

Assume thread2 gets its hands on a reference to a new Foo object without
using synchronization, as follows:

    class Bar {
        static Foo FOO;
    }

Thread 1:
    Bar.FOO = new Foo();

Thread 2:
    Foo foo = Bar.FOO;
    assert( foo == null || foo.getX() == 1 );

Question: Is it possible for thread2 to see "getX() != 1"?

If this is impossible, where is this specified in the proposed models?

I gather that using a final is preferred, as follows, and that the magic of
final even extends to "the regular fields of objects transitively reachable
from the final field". (At least that's what the CRF paper says...)

For example, plugging the version of Foo below into the scenario above,
foo.getX() will always return '1' even though the fields of the array 'a'
are not final themselves. Right?

    class Foo {
        private final int[] a = { 1 };
        int getX() { return a[0]; }
    }

--
Joe Bowbeer

------------------------------- JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:31 EDT