I have read through different articles such as Double-checked locking: Clever, but broken and I understand the reason of why the following code is broken in multi-threading usage.
class SomeClass {
private Resource resource = null;
public Resource getResource() {
if (resource == null) {
synchronized {
if (resource == null)
resource = new Resource();
}
}
return resource;
}
}
However, according to its explanation, when a thread exits a synchronized block, it performs a write barrier — it must flush out any variables modified in that block to main memory before releasing the lock. Therefore, when Thread A runs into the synchronized block, and then does the following process in order:
- Memory for the new Resource object will be allocated;
- the constructor for Resource will be called,
- initializing the member fields of the new object;
- the field resource of SomeClass will be assigned a reference to the newly created object
Finally, before Thread A exits from the synchronized block, it will write its local resource object back to the main memory and then Thread B will read this newly created resource from the main memory once it runs into the synchronized block.
Why Thread B may see these memory operations in a different order than the one Thread A executes? I thought Thread B won’t know the resource object is created until Thread A flushes its local memory out to main memory when it exits from the synchronized block because Thread B can only read the resource object from the sharable main memory?
Please correct my understanding….Thank you.
This is where it breaks down. Because Thread B accesses
resourcewithout synchronizing there is no read barrier on its operations. It may therefore see a stale cached copy of memory for theresourcecell or (a bit later) for the cell corresponding to some field of theResourceinstance.Costi Ciudatu’s fix is correct for Java versions >= 5.0. But for versions older than that the semantics of
volatiledid not guarantee that all changes would be flushed through from A to main memory to B.