Friday, 15 March 2013

java - Should I be using both lock and volatile? -



java - Should I be using both lock and volatile? -

my understanding of volatile ensures value read memory, far can see, in next example, myobject variable need volatile avoid nullpointerexception beingness raised:

private final object lock = new object(); private myobject myobject = null; //... synchronized (lock) { if (myobject == null) { myobject = new myobject(); } myobject.blah(); // other stuff want synchronized }

myobject ever touched in synchronized block. lock every used synchronize block.

is correct?

so rephrased slightly, question is...imagine 2 threads hitting code. first thread locks , sets myobject, calls .blah() , other code within synchronized block , exits synchronized block. allows thread 2 come in synchronized block. without setting myobject volatile, there chance still evaluate myobject == null true?

the synchronized block ensure updates memory seen other threads. there no need create myobject volatile.

from intrinsic locks , synchronization:

when thread releases intrinsic lock, happens-before relationship established between action , subsequent acquistion of same lock.

java locking volatile

No comments:

Post a Comment