The singleton model is not unfamiliar, it is divided into a hungry man style and lazy type.
Thread-Safe A hungry man single case
The A Hungry man-type singleton is initialized when the class is first loaded, on the code:
Public class MyObject { privatestaticnew MyObject (); Public Static MyObject getinstance () { return MyObject; }}
Here's how to verify thread safety for a hungry man-type singleton:
Public classMyThreadextendsthread{ Public voidrun () {System.out.println (Myobject.getinstance (). Hashcode ()); }} Public classTest { Public Static voidMain (string[] args)throwsException {Thread T1=NewMyThread (); Thread T2=NewMyThread (); Thread T3=NewMyThread (); T1.start (); T2.start (); T3.start (); }}
Output:
763347431763347431763347431
Three output hashcode is the same value, indicating that the A hungry man singleton is inherently thread-safe.
Conclusion: A hungry man-type singleton is initialized and thread-safe when the class is first loaded.
Non-thread-safe lazy single-case
Lazy Singleton for lazy loading, call getinstance () when it is created, on the code:
Public class MyObject { privatestaticnull;
publicstatic MyObject getinstance () { ifnull) { new MyObject (); } return myObject;} }
This situation is definitely non-thread safe. Because the object is empty and the object being created is an atomic operation, multi-threaded access produces a race condition. (Race condition: in multi-threaded concurrency, the correct result depends on the order in which multiple threads are executed)
Here's how to verify:
Public classMyThreadextendsthread{ Public voidrun () {System.out.println (Myobject.getinstance (). Hashcode ()); }} Public classTest { Public Static voidMain (string[] args)throwsException {Thread T1=NewMyThread (); Thread T2=NewMyThread (); Thread T3=NewMyThread (); T1.start (); T2.start (); T3.start (); }}
Output:
21465096838104562281996534722
Hashcode output is different, it is obvious that lazy-type singleton does not have thread safety.
Conclusion: Lazy-type singleton is initialized (initialized only once) when this instance is needed, but it is non-thread safe. In the case of a small number of cases, such a delay load and a hungry man compared to the performance of a single case there is no significant difference, so I generally do not choose this kind of primary lazy-type single case.
Volatile-based DCL scheme provides thread safety for lazy-type singleton cases
On the basis of the lazy singleton, we do some optimizations that make it a thread-safe feature.
First attempt:
Add synchronized keyword to getinstance ()
Public class MyObject { privatestaticnull;
synchronizedpublicstatic MyObject getinstance () { if null){ new MyObject (); } return myObject;} }
Output
200054444520005444452000544445
The result is a singleton, but if multiple threads call getinstance () frequently, the program execution is inefficient: The next thread wants to get the object lock and must wait until the last thread has released the lock before it can continue execution.
Second attempt:
Synchronizing code blocks
Public classMyObject {Private StaticMyObject MyObject =NULL;
Public StaticMyObject getinstance () {synchronized(MyObject.class) { if(MyObject = =NULL) {MyObject=NewMyObject (); } } returnMyObject; }}
Output
512965639512965639512965639
However, this method is equivalent to the previous attempt, the only difference is the multi-threaded, the last attempt to the middle of the thread was blocked at the door a meter at the entrance, and this time the middle of the attempt is blocked at the door half a meter at the entrance does not come in.
Third attempt:
Continue narrowing the code range for synchronization
Public classMyObject {Private StaticMyObject MyObject =NULL;
Public StaticMyObject getinstance () {if(MyObject = =NULL) {
synchronized(MyObject.class) {MyObject=NewMyObject (); } } returnMyObject; }}
Output
117575995620005444452146509683
There is a significant improvement in execution efficiency compared to the previous attempts, but no single case can be obtained. Because of the destruction of atomicity.
Fourth attempt:
The following code uses the DCL (dual check lock mechanism double checking lock)
Public classMyObject {Private StaticMyObject MyObject =NULL;
Public StaticMyObject getinstance () {if(MyObject = =NULL) {
synchronized(MyObject.class) { if(MyObject = =NULL) {MyObject=NewMyObject (); } } } returnMyObject; }}
Output:
132019484913201948491320194849
But is thread safety at this point?
no~ but I can't give a counter-example push to, we have experience, please advise ~
Fifth attempt:
We also need to add the volatile keyword to the "singleton".
Public classMyObject {volatile Private StaticMyObject MyObject =NULL; Public StaticMyObject getinstance () {if(MyObject = =NULL) { synchronized(MyObject.class) { if(MyObject = =NULL) {MyObject=NewMyObject (); } } } returnMyObject; }}
This is thread-safe.
Looking back, why does the "singleton" have to be modified with volatile?
Because the keyword volatile is able to prohibit command reordering.
Example -"singleton" in the absence of a volatile modifier, thread A and thread B are the first to invoke the Singleton method, and thread a first executes the construction method, whereas the constructor is a non-atomic operation that generates multiple instructions after compilation, and because of the order reordering, It is possible to perform an assignment first (actually returning a reference to the memory directly after opening up the area of the storage object in memory), and then the myObject is not empty, but the actual initialization operation is not yet executed, if thread B enters at this point, You will see an object that is not empty but incomplete (no initialization is completed). The volatile keyword prevents command reordering optimizations, thus enabling a safe implementation of a single case.
Conclusion: The volatile DCL scheme can preserve the characteristics of lazy loading and give the single thread security.
Static inner class implements Singleton mode
Public class MyObject { privatestaticclass holder{ Private Staticnew MyObject (); } Public Static MyObject getinstance () { return holder.myobject; }}
How to ensure thread safety? Will the command reflow cause the initialization to be incomplete because of the simultaneous invocation of getinstance () by multiple threads?
The JVM initializes classes after the class is loaded, and during initialization of classes, the JVM acquires an initialization lock that synchronizes the initialization of the same class by multiple threads, so that the command reflow is possible, but does not affect the next thread that obtains the initial lock. Because the next thread came in, the last thread has completed the initialization of the class.
Got a picture from the book:
Conclusion: The singleton pattern implemented by the static inner class can guarantee the thread safety, and has the characteristics of lazy loading. And the code is simple enough.
Java-Singleton mode and multithreading