[concurrency-interest] DCL clarification Immutable singelton

Zhong Yu zhong.j.yu at gmail.com
Wed Apr 9 21:32:25 EDT 2014


> http://stackoverflow.com/questions/14624365/immutability-and-reordering

I agree with the conclusions, however I think it is flawed to argue
that if a transformation is valid from a single-thread point of view,
it is allowed by JMM. By that argument, a perfectly good code
    if( (tmp=resource) != null )
        return tmp;
can be transformed to a very bad code
    if( resource != null )
        return resource;   // [r1]
since they are equivalent in single-thread.

JMM only talks about reads/writes in the program source. Here [r1] did
not exist in the program source, how could the compiler reason about
its effect? Can the compiler ever introduce such ghost reads with
confidence of correctness?

Back to the original problem, can this code
    if( resource != null )
        return resource;
be transformed to
    tmp = resource;  // [r2]
    if( resource != null )
        return tmp;
? The compiler now does two reads unconditionally; [r2] would be a
ghost read that did not exist in the source, unless the if() condition
is true, but how could the compiler reach that prediction?

Zhong Yu


More information about the Concurrency-interest mailing list