My understanding of volatile is that it ensures that the value is always read from memory, so as far as I can see, in the following example, the myObject variable would need to be volatile to avoid a NullPointerException being raised:
private final Object lock = new Object();
private MyObject myObject = null;
//...
synchronized (lock) {
if (myObject == null) {
myObject = new MyObject();
}
myObject.blah();
// some other stuff that I want synchronized
}
myObject is only ever touched in the synchronized block. lock is only every used to synchronize that block.
Is that correct?
So rephrased slightly, my question is...imagine two threads are hitting that code. First thread locks and sets myObject, calls .blah() and any other code within the synchronized block and exits the synchronized block. This allows thread two to enter the synchronized block. Without setting myObject to volatile, is there are chance it could still evaluate myObject == null to true?