I have no other hands, but I am familiar with it! Multi-threaded Singleton Design Mode
As we all know, in singleton mode, constructor is private and calls constructor internally through static methods to return instance objects of this class. The common code is as follows:
?
| 12345678910 |
public class Singleton { private
static Singleton singletonObj;
private
Singleton(){} public
static Singleton getInstance(){ if(singletonObj ==
null){ singletonObj =
new Singleton(); } return
singletonObj; }} |
In the case of a single thread, there is indeed only one instance, but in the case of multiple threads, unexpected situations will occur.
Create a testsingleton class as follows:
?
public class TestSingleton implements
Runnable { private
Singleton s = null; public
Singleton getS() { return
s; } public
void setS(Singleton s) { this.s = s; } public
static void main(String[] args) { TestSingleton ts1 =
new TestSingleton(); TestSingleton ts2 =
new TestSingleton(); Thread t1 =
new Thread(ts1); Thread t2 =
new Thread(ts2); t1.start(); t2.start(); Singleton s1 = ts1.getS(); Singleton s2 = ts2.getS(); System.out.println(s1 == s2); } @Override public
void run() { s = Singleton.getInstance(); }} |
The running result returns false.
In a multi-threaded environment, you need to consider the synchronization problem and modify the code in the singleton mode as follows:
?
public static Singleton getInstance() { if
(singletonObj == null) { synchronized
(Singleton.class) { if
(singletonObj == null) { singletonObj =
new Singleton(); } } } return
singletonObj; } |
Re-run testsingleton and return the result "true" to ensure that the singleton mode is correct even in a multi-threaded environment.