Java singleton approach is allowing more than one instance of the object

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?

Answer

In your example, tmp and tmp1 is the same object instance. You can check it by printing both objects :

System.out.println(tmp);
System.out.println(tmp1);

After, you call the method on same object twice, and counter is incremented twice. But only one object of Singleton was created

Leave a Reply

Your email address will not be published. Required fields are marked *