2

This is a followup from Java double checked locking.

The following code snippet has 2 interesting characteristics.

1) It requires a call to a separate init() method before the object is ready for use. So volatile doesn't help (I know, why don't I just put the code in init() into the constructor? It's here for the purposes of illustration).

2) It uses a tmp variable to do the initialization and assigns to instance after initialization is complete.

if (instance == null) {
synchronized (mutex) {
    if (instance == null) {
        AClass tmpInstance = new AClass();
        tmpInstance.init();
        instance = tmpInstance;
    }
}
}

So, is this subject to the reordering problem, i.e., could instance be assigned to tmpInstance prior to tmpInstance.init() being called?

Thanks, Rich

2 Answers 2

2

All that matters is that you are assigning to instance as the last operation, after all initialization is done. Since instance is (hopefully) volatile, this will ensure all initialization is visible to later readers.

BTW there is really no need for you to learn all the rules of allowed reorderings: that's compulsory reading only for JIT compiler implementors.

All you, as a Java programmer, need to keep in mind are the two simple guarantees that the Java Memory Model offers you (one is about synchronized, the other about volatile). The whole point of the JMM rewrite (as of JLS 3) was to allow us to program against a very simple concurrency model.

1

So, is this subject to the reordering problem, i.e., could instance be assigned to tmpInstance prior to tmpInstance.init() being called?

No but it is subject to the visibility problem which volatile does solve. So you should still declare instance volatile.

Now the reason why it is not subject to a reordering. Normal stores cannot be reordered after a monitor enter.

http://g.oswego.edu/dl/jmm/cookbook.html

1st Operation: MonitorEnter

2nd Operation: NormalStore

Can Reorder: No

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.