Monday, October 28, 2013

Singleton in multi threaded environment ? example of asynchronous, threads creating two or more objects to singleton.

Hi All,

In this post I am going to give an example of singleton class which is not thread safe and leads to create multiple objects by multiple threads..

Classes:

Singleton.java
Creator.java
Creator1.java
Test.java


Singleton.java
---------------------
public class Singleton {

private static Singleton s;
public static int count = 0;

private Singleton() {
count++;
}

public static Singleton getInstance() {
if (null == s) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

s = new Singleton();

}
return s;
}
public void display(){

System.out.println("hi");
}

}//end class

---------------------------------------------------------------------------------------------------------

Creator.java
---------------

public class Creator extends Thread {

@Override
public void run() {
Singleton s = Singleton.getInstance();
s.display();
}

}//end class

---------------------------------------------------------------------------------------------------------

Creator1.java
-----------------

public class Creator1 extends Thread {

@Override
public void run() {
Singleton s = Singleton.getInstance();
s.display();
}

}//end class

---------------------------------------------------------------------------------------------------------

Test.java
------------

public class Test {

public static void main(String[] args) throws InterruptedException {

Creator c = new Creator();
Creator1 c1=new Creator1();
c1.start();
c.start();
Thread.sleep(600);

System.out.println(" number of threads created is:" + Singleton.count);

}
}//end class



If you run the above Test class, the output will be like below

trail 1: 
hi
hi
 number of threads created is:1

trail 2:
hi
hi
 number of threads created is:2

trail 3:
hi
hi
 number of threads created is:2


....and so on..

Here even though we have made singleton class, In multi threaded environment, there is a chance of creating two objects / calling constructors two times  by multiple threads.