Singleton pattern interview

java, singleton

Solution

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

Problem

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 - More than one instance of Bolton can be created - A Bolton 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 Which of the above options is correct? And Why?

Original source

Related problems