[concurrency-interest] RE: Synchronization of data read bymultiplethreads

David Holmes dholmes at dltech.com.au
Sun Oct 30 20:10:08 EST 2005

Larry writes:
> > If the thread doing the construction publishes the reference to the
> > newly constructed object in an unsafe manner (ie without
> > then other threads accessing the object need not see the constructed
> > state of its fields (unless they are final or volatile).
> Would it be easy to provide an example which demonstrates
> this (another thread seeing the inchoate state)?


 class X {
     public static theX;

     // fields with non-default initialization (or done through constructor
     Object a = new Object();
     int b = 54;
     long c = 0x1234567812345678L;

      Thread-A                                 Thread-B
     X.theX = new X();

Thread-B could print either 0 or 54.

When ever one thread creates an object and then 'publishes' that reference
for other threads to see, and the publishing does not involve any
synchronization, then there is no happens-before relationship between the
construction of the object and the use of it in a different thread.

The above example can be fixed by making theX volatile, or by providing a
synchronized accessor and settor for theX.

David Holmes

More information about the Concurrency-interest mailing list