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:
UnsafeLazyInitialization
is actually safe ifResource
is immutable.
I don't understand that statement:
- If
Resource
is immutable, any thread observing theresource
variable 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
resource
could be reordered (there is one read in theif
and one in thereturn
). So a thread could see a non nullresource
in theif
condition 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:
question from:https://stackoverflow.com/questions/14624365/immutability-and-reorderingWhat 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!