There is something wrong with my code below. I am getting multiple instances of the same singleton class when calling it from multiple threads from the same process. I am expecting the program should print "Creating instance" only once but it is printing 3 times(i.e. per thread).
package SingleTon;
class SingleTon implements Runnable {
String name;
int salary;
private static SingleTon singleTonInstance;
SingleTon() {
}
public static SingleTon getInstance() {
if (singleTonInstance == null) {
synchronized (SingleTon.class) {
System.out.println("Creating instance");
singleTonInstance = new SingleTon();
}
}
return singleTonInstance;
}
@Override
public void run() {
System.out.format("Thread %s is starting\n",Thread.currentThread().getName());
getInstance();
}
}
package SingleTon;
public class SingleTonDemo {
public static void main(String[] args) {
System.out.println("test");
SingleTon t = new SingleTon();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.start();
t2.start();
t3.start();
}
}
Output:
test
Thread Thread-0 is starting
Thread Thread-2 is starting
Thread Thread-1 is starting
Creating instance
Creating instance
Creating instance