Problem
in Approach 2
In
a Multi threaded Environment, Above code won't work.
Lets
take a scenario, there are two threads t1 and t2 calls the
getInstance method. Lets us assume, t1 got a chance first to enter
into getInstance method, After checking for the condition(instance
== null) which is true, it swapped out, and t2 come in, now for t2
also the condition (instance == null) is true, so there are two
instances got created.
For
Example, let us update the program to support threads.
class SingleTon{
static SingleTon instance;
private SingleTon(){
}
public static SingleTon getInstance(){
if(instance == null){
instance = new SingleTon();
}
return instance;
}
}
class SingleTonTest extends Thread{
SingleTon obj;
public void run(){
obj = SingleTon.getInstance();
}
public static void main(String args[])throws Exception{
SingleTonTest t1 = new SingleTonTest();
SingleTonTest t2 = new SingleTonTest();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.print("Is t1.obj and t2.obj point to same object ");
System.out.println((t1.obj==t2.obj));
}
}
On
Multiple runs the output is like below.
Run
1:
Is
t1.obj and t2.obj point to same object false
Run
2:
Is
t1.obj and t2.obj point to same object false
Run
3:
Is
t1.obj and t2.obj point to same object false
Run
4:
Is
t1.obj and t2.obj point to same object true
Run
5:
Is
t1.obj and t2.obj point to same object true
Run
6:
Is
t1.obj and t2.obj point to same object false
Approach
3
To
solve the above problem, why can't we use synchronization. Looks like
a good idea. Now change the code like below.
class SingleTon{
static SingleTon instance = null;
private SingleTon(){
}
public static SingleTon getInstance(){
synchronized(SingleTon.class){
if(instance == null){
instance = new SingleTon();
}
}
return instance;
}
}
class SingleTonTest extends Thread{
SingleTon obj;
public void run(){
obj = SingleTon.getInstance();
}
public static void main(String args[])throws Exception{
SingleTonTest t1 = new SingleTonTest();
SingleTonTest t2 = new SingleTonTest();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.print("Is t1.obj and t2.obj point to same object ");
System.out.println((t1.obj==t2.obj));
}
}