Why the double lock Singleton pattern to add volatile (rpm)

Singleton follows:

 

 Reasons to volatile keyword is in the concurrent case, if not volatile keyword, the problem will appear on line 5.

instance = new TestInstance (); it can be divided into three lines pseudocode

a.memory = allocate () // allocate memory

b. ctorInstanc (memory) // initialize objects

c. instance = memory // set the address instance points to just assigned

The above code at compile and run time, there may be reordered from abc order of acb. Following problem arises in the case of multi-threaded. When the thread A executes lines of code 5, B to perform thread coming second line code. Assuming that A occurs during execution of an instruction reordering, i.e., a first and C performed, not performed b. A thread of execution, then since the point c instance led to some address, it is determined instance thread B is not null, will directly jump to line 6 and return an uninitialized objects.

 

 

Editor: double lock Singleton pattern why should we increase volatile

Guess you like

Origin www.cnblogs.com/heqiyoujing/p/11610654.html