Volatile in double check locking in Java
See English answers > why is volatile used in double checked locking
class Foo { private volatile Bar _barInstance; public Bar getBar() { if (_barInstance == null) { synchronized(this) { // or synchronized(someLock) if (_barInstance == null) { Bar newInstance = new Bar(); // possible additional initialization _barInstance = newInstance; } } } return _barInstance; } }
Suppose you can only access it through getbar_ Barinstance, I want to know whether the lack of volatile is a serious error, or just a minor defect of a possible performance defect
My thoughts are as follows: synchronized introduces the relationship before it happens Initialization_ The thread of barinstance writes its value into main memory instead of synchronization block Therefore, even if it is not volatile, it will not have_ Double initialization of barinstance: other threads_ The local copy of barinstance is empty (true in the first check), but the new value must be read from the main memory in the second check and checked after entering the synchronized block (get false and do not reinitialize) So the only problem is that each thread gets too many locks
As far as I know, it is correct in CLR, and I believe it is also correct in JVM Am I right?
thank you.
Solution
Not using volatile may cause errors in the following cases:
>Thread 1 enters getbar() and finds_ Barinstance is null > thread 1 attempts to create a bar object and update the pair_ Reference to barinstance Due to some compiler optimizations, these operations may not be sequential. > At the same time, thread 2 enters getbar () and sees non null_ Barinstance, but it may be in_ See the default value in the member field of the barinstance object It basically sees a partially constructed object, but the reference is not null
The volatile modifier disables writing or reading variables relative to any previous read or write_ barInstance. Therefore, it will ensure that thread 2 does not see partially constructed objects
For more information: http://www.cs.umd.edu/ ~pugh/java/memoryModel/DoubleCheckedLocking. html