The code below (Java Concurrency in Practice listing 16.3) is not thread safe for obvious reasons:
public class UnsafeLazyInitialization {
private static Resource resource;
public static Resource getInstance() {
if (resource == null)
resource = new Resource(); // unsafe publication
return resource;
}
}
However, a few pages later, in section 16.3, they state:
UnsafeLazyInitializationis actually safe ifResourceis immutable.
I don’t understand that statement:
- If
Resourceis immutable, any thread observing theresourcevariable will either see it null or fully constructed (thanks to the strong guarantees of final fields provided by the Java Memory Model) - However, nothing prevents instruction reordering: in particular the two reads of
resourcecould be reordered (there is one read in theifand one in thereturn). So a thread could see a non nullresourcein theifcondition but return a null reference (*).
I think UnsafeLazyInitialization.getInstance() can return null even if Resource is immutable. Is it the case and why (or why Not)?
(*) To better understand my point about reordering, this blog post by Jeremy Manson, who is one of the authors of the Chapter 17 of the JLS on concurrency, explains how String’s hashcode is safely published via a benign data race and how removing the use of a local variable can lead to hashcode incorrectly returning 0, due to a possible reordering very similar to what I describe above:
What I’ve done here is to add an additional read: the second read of hash, before the return. As odd as it sounds, and as unlikely as it is to happen, the first read can return the correctly computed hash value, and the second read can return 0! This is allowed under the memory model because the model allows extensive reordering of operations. The second read can actually be moved, in your code, so that your processor does it before the first!
The confusion I think you have here is what the author meant by safe publication. He was referring to the safe publication of a non-null Resource, but you seem to get that.
Your question is interesting – is it possible to return a null cached value of resource?
Yes.
The compiler is allowed to reorder the operation like such
This doesn’t violate the rule of sequential consistency but can return a null value.
Whether or not this is the best implementation is up for debate but there is no rules to prevent this type of reordering.