Singleton mode is probably the most commonly used design pattern in our normal work. The problem solved by the singleton pattern is also common, that is, how to create a unique object. But it's not easy to create it safely, but it also requires some thinking and understanding of the JVM.
1. First, the textbook tells me that the single case is written
1 Public classSingleton {2 3 Private StaticSingleton instance;4 5 PrivateSingleton () {6 }7 8 Public StaticSingleton getinstance () {9 if(Instance = =NULL) {TenInstance =NewSingleton (); One } A returninstance; - } -}
The biggest problem with this code is that it's not thread-safe. That is, multiple objects may be new in the case of multithreading. Imagine two threads executing to line 9th, because there is no lock mechanism, then two threads will enter, will be new out of multiple objects.
1 Public StaticCountdownlatch latch =NewCountdownlatch (2);2 3 Public Static voidMain (string[] args) {4 for(inti = 0; I < 2; i++) {5 NewThread (NewRunnable () {6 7 @Override8 Public voidrun () {9 Latch.countdown ();Ten Try { One latch.await (); A}Catch(interruptedexception e) { - //TODO auto-generated Catch block - e.printstacktrace (); the } - System.out.println (Singleton.getinstance ()); - } - }). Start (); + } -}
I use the above code to illustrate the results of the first single-instance notation. Finally, the ToString method of object is called to print the hashcode of the singleton object
The results are as follows
First result: [email protected][email protected]11989480 Second result: [email protected][email protected] Third result: [email Protected][email protected] Fourth time result: [email protected][email protected] Fifth result: [email protected][email protected]
As you can see, the Singleton Code 1 does have a situation where there are multiple objects in the new instance.
The GetInstance method of the single example code 1 is changed to the following, the GetInstance method plus synchronized keyword
public static synchronized Singleton getinstance () {
if (instance = = null) {
Instance = new Singleton ();
}
return instance;
}
Here are 5 test results
First: [email protected][email protected] The second time [email Protected][email protected] The third time [email protected]com.deng.pp.sin[ Email protected] Fourth [email Protected][email protected] fifth time [email protected][email protected]
You can be sure that synchronized really works. This can work, and there is nothing wrong with the results. But it has one of the biggest problems is the efficiency problem. Each thread calls the GetInstance method to determine if there are other threads executing this method, even if the instance already exists and needs to determine if the thread is in the method. If you have one, you should wait outside. In fact, you just need to wait before the new object. According to this, there is the following method: Double check lock
1 Public StaticSingleton getinstance () {2 if(Instance = =NULL) {3 synchronized(Singleton.class) {4 if(Instance = =NULL) {5Instance =NewSingleton ();6 }7 }8 }9 returninstance;Ten}
To analyze, assuming that two threads reach the GetInstance method, thread 1 first obtains the lock and enters the initialization method. Thread 2 because the lock is not obtained outside waiting, thread 1 out, thread 2 into the synchronization block, instance is not Null,return, perfect.
However, the result may not be the case because the new operation of the object is not atomic . The process for the JVM new object is roughly the following
1. Allocate a chunk of memory space on the heap 2. Instantiate the class into 1 allocated memory space 3. Assigning references to instance
If you follow the 123 order, the above code is no problem. However, there is a command rearrangement in the JVM, that is, the compiler optimizes the code to change the order in which the code does not depend on each other. The third step in the above-mentioned three steps does not depend on the second step, i.e. there may be 132 in this order.
So in this order, thread 1 executes to 3. Thread 2 enters the method, which is not NULL because instance has been assigned a value. Return directly, this time the object of return is incorrect, because thread 1 has not completely initialized the object.
(I'm sorry that I didn't reproduce the problem in my environment, but if there are other ways to test the problem, please don't hesitate to enlighten me.) )
The workaround is to change the instance field to
Private volatile static Singleton instance;
The volatile keyword prevents order reordering, thus guaranteeing a single case of correctness.
The following method can also be implemented as a singleton, because Singleton is static so it is initialized when the class is loaded, and final guarantees that the value will be assigned only once. Small projects can be used, very convenient, a lot of time if all the load may be a waste of resources.
Public Static Final New Singleton ();
Effective Java authors recommend a better, more secure way to write.
Public class Singleton { private Singleton () { } publicenum instance{ Instance; Private Singleton Singleton; Instance () { new Singleton (); } Public Singleton getinstance () { return Singleton;}} }
Recently began to write a blog, Caishuxueqian, such as the text of any errors please message exchange. Thank you ~
Write a safe Java single case