Java Singleton Design pattern Question & Answer

Java Singleton Design pattern Question & Answer.

Q1. What is the Significance of Classloader in Singleton Pattern?

Ans1. If singleton class is loaded by two classloaders, two instance of singleton class will be created, one for each classloader.

Q2. What is the significance of Serialization in Singleton Pattern?

Ans2.  If a singleton class is serializable, than you can serialize singleton instance but this will not return singleton object. Once it is serialized than you can deserialize it but it will not return the singleton object.

To resolve this issue, we need to override the readResolve() method that enforces the singleton. It is called just after the object is deserialized. It returns the singleton object.

package basicsingleton;

import java.io.Serializable;

public class Singleton implements Serializable{

private static Singleton obj = null;

protected Singleton readResolve() {

return getInstance();

}

 

private Singleton() {

}

public static synchronized Singleton getInstance() {

if (null == obj) {

obj = new Singleton();

}

return obj;

}

}

 

Q3. How many forms to create singleton design pattern?

Ans3. There are two forms two create singleton design pattern.

  1. Early Instantiation à Class load time
  2. Lazy Instantiation à when required create object.

Q4. Where we can use singleton design pattern?

Ans4. Singleton pattern is mostly used in multi-threaded and database applications. It is used in logging, caching, thread pools, configuration settings etc.

Q5. What is the worst thing with following code?

public class Test {

private static Test INST = null;

public static Test getInstance()

{

if ( INST == null )

{

INST = new Test ();

}

return INST;

}

private Test() {

}

}

 

Ans5. 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 More than one instance of Bolton can be created.

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

 

public class Test {

private static volatile Test instance = null;

private Test () {  }

public static Test getInstance() {

if (instance == null) {

synchronized (Test.class){

if (instance == null) {

instance = new Test ();

}

}

}

return instance;

}

}

java

Leave a Reply

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