Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private constructor and instances - Multiple choice

Tags:

java

singleton

I am trying to figure out the answer to the following MC question. I have tried looking for an answer on google but people seem to have different answers for this problem. Can someone please explain their answer.

public class Gingleton {
    private static Gingleton INSTANCE = null;

    public static Gingleton getInstance()
    {
        if ( INSTANCE == null )
        {
            INSTANCE = new Gingleton();
        }
        return INSTANCE;
    }

    private Gingleton() {
    }
}
  • More than one instance of Gingleton can be created (My choice)

  • A Gingleton will never be created

  • The constructor is private and can't be called

  • value can be garbage collected, and the call to getInstance may return garbage data

like image 433
user3353723 Avatar asked Dec 13 '25 11:12

user3353723


1 Answers

New instance creation in getInstance() is not synchronized in any way, so it IS possible that more than one instance will be created in mulithreaded environment. To ensure only one instance you should do:

public class Gingleton {

    // volatile
    private static volatile Gingleton INSTANCE = null;

    public static Gingleton getInstance()
    {
        if ( INSTANCE == null )
        {
            synchronized (Gingleton.class) {  // Synchronized
                if ( INSTANCE == null )
                {
                    INSTANCE = new Gingleton();
                }
            }
        }
        return INSTANCE;
    }

    private Gingleton() {
    }
}
like image 97
Mariusz Jamro Avatar answered Dec 15 '25 03:12

Mariusz Jamro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!