Now read the Java Concurrency Book, record it. For the Java singleton pattern, the correct code should be:
public class Testinstance { Private volatile static testinstance instance; public static Testinstance getinstance () {//1 if (instance = = null) { //2 synchronized (testinstance.class) {//3 if (instance = = null) {//4 instance = new Testinstance ();//5 }}} return instance;//6< c11/>}}
It was not previously understood why the volatile keyword was needed and later found that in the concurrency scenario, if there is no volatile keyword, there is a problem in the 5th row
For line 5th
= new Testinstance ();
Can be decomposed into 3 lines of pseudo-code
1 memory=allocate ()///Allocate memory equivalent to malloc for C
2 Ctorinstanc (memory)/Initialize Object
3 Instance=memory//Set instance point to the address you just assigned
The above code may appear reordering from 1-2-3 when the compiler is running to 1-3-2
This will cause problems in multiple threads
For example, there are 2 threads, A, b
When thread a executes the 5th line of code, the B thread comes in, and at this point a executes 1 and 3 without executing 2, and the B thread determines that instance does not return an uninitialized object directly, and there is a problem
With volatile, the above reordering will be banned in multi-threaded environments without the above problems.
Java Singleton mode, why do I need volatile