Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern interview

Tags:

java

singleton

I am recently asked about java related question in an interview with following code, since I am very new to java and barely code in Java so I really have no idea what the following code does.

The question was Select the option that describes the worst thing with the following code:

public class Bolton {
    private static Bolton INST = null;

    public static Bolton getInstance()
    {
        if ( INST == null )
        {
            INST = new Bolton();
        }
        return INST;
    }

    private Bolton() {
    }
}

Here are the options for this question

  1. More than one instance of Bolton can be created
  2. A Bolton will never be created
  3. The constructor is private and can't be called
  4. Value can be garbage collected, and the call to getInstance may return garbage data

Which of the above options is correct? And Why?

like image 362
Om3ga Avatar asked Mar 15 '13 05:03

Om3ga


People also ask

What is singleton pattern used for?

Singleton pattern is used for logging, drivers objects, caching and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc. Singleton design pattern is used in core java classes also, for example java. lang.

Why You Should Avoid singleton?

The most important drawback of the singleton pattern is sacrificing transparency for convenience. Consider the earlier example. Over time, you lose track of the objects that access the user object and, more importantly, the objects that modify its properties.

What problem does singleton pattern solve?

In the case of logging data to a file, we may have multiple clients logging to a single file at the same time. The singleton pattern can help prevent problems with concurrent access to this log file.

What is Singleton design pattern real time example?

Singleton is like a single resource which is being shared among multiple users; for example - sharing a single washing machine among all the residents in a hotel or sharing a single appliance like refrigerator among all the family members.


2 Answers

This is a Singleton Pattern

The idea of a Singleton Pattern is to only have one available instance of a class. Therefore the constructor is set to private and the class maintains, in this case, a getInstance() method that either calls an existing instance variable, INST in this class, or creates a new one for the executing program. The answer is probably 1, because it's not thread safe. It may be confused for 3, which I had put down earlier, but that is by design, technically, so not actually a flaw.

Here's an example of Lazy Initialization, thread-safe singleton pattern from Wikipedia:

public class SingletonDemo {

    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {  } 

    public static SingletonDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonDemo.class){
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }
        return instance;
    }

}

Setting the instance variable to volatile tells Java to read it from memory and to not set it in cache.

Synchronized statements or methods help with concurrency.

Read more about double checked locking which is what happens for a "lazy initialization" singleton

like image 187
SomeShinyObject Avatar answered Nov 10 '22 05:11

SomeShinyObject


More than one instance of Bolton can be created

This option is correct due to lack of synchronization in the above code.

Suppose two threads concurrently check for null and both will find that the value is null and both will call the constructor (which refutes singleton).

Also there is other catch in this, even if two threads dont check for null together but suppose one thread calls the constructor; but the constructor wont return till the object is constructed (assuming that the object is costly to create and requires time), so till the constructor returns some other thread might check for the null condition and still find the object as null as the object is not yet constructed.

This scenario in which some pre condition is called check-then-act which is culprit for Race.

For singleton there are two standards that are being used:

  • Double Checked locking
  • Enum based singleton pattern

UPDATE: Here is another great article which discusses the double checked locking

like image 20
Narendra Pathai Avatar answered Nov 10 '22 07:11

Narendra Pathai