[concurrency-interest] Reordering and Immutability

David Holmes davidcholmes at aapt.net.au
Sun Feb 3 16:21:20 EST 2013

Yann Le Tallec writes:
> I have a couple of questions regarding the following class:
> public class SomeClass {
>   private static Resource resource = null; //w0
>   public static Resource getInstance() {
>     if (resource == null)                  //r1
>       resource = new Resource();           //w1
>     return resource;                       //r2
>   }
> }
> (1) Can getInstance() return null?

As Vitaly described there is a transformation that could cause null to be
returned. Establishing the legality, or not, of such a transformation is
very difficult as there is no Java source to Java bytecode compilation
specification. The transformation does not seem sensible but that doesn't
mean it is prohibited.

> (2) Same question with resource declared as "private static Resource
> resource;" (without the "= null") and with the additional assumption
> that Resource is immutable
> - I am told that "Resource resource; can't race whereas Resource
> resource = null; can", but I don't see why they are different from a
> JMM perspective.

There is no difference. "Resource resource;" implicitly sets resource to
null during static initialization of the class.

> - The resource variable being non-final, I don't think immutability
> makes a difference here as null is still a valid and observable value.

Immutability, through final fields, is more concerned with safe-publication
of the object. If you can get a reference to it then you are guaranteed to
see it properly constructed, if it is immutable.

> ps: JCiP has an UnsafeLazyInitialization example similar to SomeClass
> (without the "=null") and states in 16.3 that it would be safe if
> Resource were immutable, so I guess I'm missing something and that
> null is not a possible outcome.

The JCiP example is not considering null as a possible outcome and is only
looking at the safe-publication aspect.

David Holmes

> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest

More information about the Concurrency-interest mailing list