I wrote the following code initially. The purpose was to ensure only one object of a class is created at any point of time.
public class singleinstance {
private static int instance;
public singleinstance(){
if(instance != 0){
throw new IllegalStateException("More than one instance");
}
System.out.println(instance);
instance ++;
System.out.println(instance);
}
}
later, when I checked internet to see if this is the best way to do this, I came across the term singleton
, and using private constructors, and came across This link
I tried the same code in its accepted answer section, but by defining a counter variable and printing it, and could see that the number of instance of class is more than one. I am pasting the code below.
public class Singleton {
private static int counter=0;
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public int demoMethod() {
counter++;
return counter;
}
}
Singletontest.java
public class Singletontest {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
System.out.println(tmp.demoMethod());
Singleton tmp1 = Singleton.getInstance();
System.out.println(tmp1.demoMethod());
}
}
The test class, when executed, printed 1
, 2
, which means two instances of the class is created with the singleton class. If this is possible, why is it considered singleton? Please clear my understanding.
EDIT::
the call to the method incremented the value again. But again, I could alternately call the methods tmp1.demoMethod(), tmp.demoMethod()
multiple times, which made me think that tmp and tmp1 are the two objects that are created. How do I confirm, or what are the things that I can look into, to confirm that this is just a single instance?