I am trying to implement an example of the singleton pattern. One of our questions is to run two threads each calling getInstance() and to verify only one instance of the Singleton object was created.
Here is my Singleton code;
public class OurSingleton {
static OurSingleton ourSingleton;
static int instanceCounter;
private OurSingleton(){
instanceCounter++;
}
public static synchronized OurSingleton GetSingletonInstance(){
if( ourSingleton == null){
ourSingleton = new OurSingleton();
}
return ourSingleton;
}
public static int getCounter() {
return instanceCounter;
}
}
And my main;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
OurSingleton mySingleton = null;
Thread one = new Thread(new GetSingletonInstance(mySingleton));
Thread two = new Thread(new GetSingletonInstance(mySingleton));
one.start();
two.start();
System.out.println("Main: " + mySingleton.getCounter());
}
}
class GetSingletonInstance implements Runnable {
int count = 0;
OurSingleton singleton;
public GetSingletonInstance(OurSingleton ourSingleton){
singleton = ourSingleton;
}
@Override
public void run() {
try {
while (count < 5000000) {
singleton.getSingletonInstance();
count++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Thread: " + singleton.getCounter());
}
}
When I run this code I get the following output;
Main: 0 Thread: 1 Thread: 1
Can somebody explain the reason for this output? I thought only a single instance of Singleton existed across the board. Does this mean another object is being created in the threads ?? Any advice is appreciated !
There is only one
OurSingletoninstance, but the classgetSingletonInstance(USE PROPER CAPS!) is not a singleton itself. And it is the one where you put the counter.