April 26, 2016

Part 2: Java Design Pattern Interview Questions & Answers (All About Singleton Design Pattern)

In Part 1 of Java Design Pattern Interview Questions & Answers, we discussed the basics. Now in Part 2, we will discuss the Singleton design pattern in detail. 

What is the Singleton pattern?

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

This pattern involves a single class that is responsible to create an object while making sure that only a single object gets created. This class provides a way to access its only object which can be accessed directly without the need to instantiate the object of the class.

There are many classes in JDK which is implemented using Singleton pattern like : Java.lang.Runtime with getRuntime() method, Java.awt.Toolkit with getDefaultToolkit() and Java.awt.Desktop with getDesktop() etc.

How can you create a Singleton class in Java?

It is quite simple, you can do it in just two steps:
  • First, make the constructor private so that the new operator cannot be used to instantiate the class. 
  • Create a method that will return an object of the singleton if not null, otherwise, create the object and return the same.
Example:

 

What is the difference between a static class and a singleton class?

  • A static class can not implement interfaces whereas a singleton class can.
  • All members of a static class are static but for a Singleton class, it is not a requirement.
  • A static class gets initialized when it is loaded so it can not be lazily loaded whereas a singleton class can be lazily loaded.
  • A static class object is stored in a stack whereas a singleton class object is stored in heap memory space.
  • We can clone the object of Singleton but, we can not clone the static class object.

Why can’t we use a static class instead of a singleton?

  • Singleton class can implement interfaces and extend classes while the static class cannot (it can extend classes, but it does not inherit their instance members). If we consider a static class it can only be a nested static class as a top-level class cannot be a static class. Static means that it belongs to a class it is in and not to any instance. So it cannot be a top-level class.
  • The static class will have all its members as static only unlike Singleton.
  • It can be lazily loaded whereas static will be initialized whenever it is first loaded.
  • Singleton object stores in Heap but, static object stores in the stack.
  • We can clone the object of Singleton but, we can not clone the static class object.

Which is better in Java, implementing public static methods or a singleton class?
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), a singleton is an appropriate choice for you whereas the static method is used when you need a function (Receive inputs then return an output).

The advantage of a singleton is that when in the future you decide that this object should no longer be a singleton (due to new insights or new requirements), it is easier to refactor it( we just need to change all the places that get the instance, instead of all calls to the static methods).

Can we create a clone of a singleton object?

Yes.

How to prevent the cloning of a singleton object?

Throw exception within the body of the clone() method.

What is double-checked locking in Singleton?

Double-checked locking is a technique to prevent creating another instance of Singleton when the call to getInstance() method is made in a multi-threading environment. 



Explain in a singleton pattern whether it is better to make the whole getinstance() method synchronized or just critical section is enough? Which one is preferable?

Synchronization of the whole getinstance() method is costly and is only needed during the initialization on a singleton instance, to stop creating another instance of Singleton.  Therefore it is better to only synchronize the critical section and not the whole method.

What is the lazy and early loading of Singleton and how will you implement it?

As there are many ways to implement Singleton like using double-checked locking or Singleton class with static final instance initialized during class loading. The former is called lazy loading because the Singleton instance is created only when the client calls getInstance() method while the latter is called early loading because the Singleton instance is created when the class is loaded into memory.

How do you prevent creating another instance of Singleton during serialization?

You can prevent this by using the readResolve() method since during serialization readObject() is used to create an instance and it returns a new instance every time but by using readResolve you can replace it with the original Singleton instance.


How many ways you can write Singleton Class in Java?

a. Singleton by synchronizing getInstance() method
b. Singleton with public static final field initialized during class loading.
c. Singleton generated by the static nested class, also referred to as Singleton holder pattern.
d. From Java 5 onwards using Enums

How to create a singleton class in Java using ENUM?

Though the Singleton pattern in Java exists for a long time Enum Singletons are a relatively new concept and in practice from Java 5 onward after the introduction of Enum as a keyword and feature.

In this way, you can create a singleton class using enum, if you want you can declare instance variable and instance method inside it. If you are using an instance method then you need to ensure thread-safety of that method if at all it affects the state of the object. By default creation of Enum instance is thread-safe but any other method on Enum is the developer's responsibility.

Whenever you want an instance of a singleton class, call MySingleton.INSTANCE. It is much easier than calling getInstance() method on Singleton.

Why Enum Singleton is better in Java?

1). Enum Singleton is easy to write and Enum instance is thread-safe.

Suppose you want to implement singleton class with double checked locking, then you need to write getInstance() method as:

public MySingletonDoubleCheckedLocking getInstance(){
    if(INSTANCE == null){
        synchronized(MySingletonDoubleCheckedLocking.class){
                if(INSTANCE == null){
                    INSTANCE = new MySingletonDoubleCheckedLocking();
                }
            }
         }
     return INSTANCE;
}


There is one more way to create a singleton class in Java, by using the static factory method. This Singleton instance is a static and final variable, it is initialized when class is first loaded into memory so the creation of instance is inherently thread-safe. You can call MyStaticSingleton.getSingleton() to get access to this class.

public class MyStaticSingleton{
    //initailzed during class loading
    private static final MyStaticSingleton INSTANCE = new MyStaticSingleton();

    //to prevent creating another instance of MyStaticSingleton
    private MyStaticSingleton(){}

    public static MyStaticSingleton getSingleton(){
        return INSTANCE;
    }
}


In both the above ways we need to write so many lines of code in getInstance(), but with the Enum Singleton pattern, we can have that in just one line because the creation of the Enum instance is thread-safe and guaranteed by JVM.

2). Enum Singletons handled Serialization by themselves.

If you are using the conventional way to create a singleton class and implement Serializable interface, then you need to take extra care because the readObject() method always returns a new instance just like the constructor in Java. You need to add readResolve() method in the singleton class, which discards the newly created instance by replacing it with Singleton. e.g:

private Object readResolve(){
    return INSTANCE;
}


This can become even more complex if your Singleton Class maintains state, as you need to make them transient, but with Enum Singleton, Serialization is guaranteed by JVM.

What are the problems with enum as a singleton?

  • enums do not support lazy loading.
  • Though it’s very very rare if you changed your mind and now want to convert your singleton to multi-ton, enum would not allow this.

How to prevent Singleton Pattern from Reflection?

Reflection can be caused to destroy singleton patterns. To overcome this issue enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible (it does not allow lazy initialization).

Enums don’t have any constructor so it is not possible for Reflection to utilize it. Enums have their by-default constructor, we can’t invoke them by ourselves. JVM handles the creation and invocation of enum constructors internally. As enums don’t give their constructor definition to the program, it is not possible for us to access them by Reflection also. Hence, reflection can’t break singleton property in the case of enums.

Give an example scenario where you will use a singleton pattern.

  • Assume what we are writing an application that needs to log events in a log file. Logging is done with the timestamp. We do not want to have more than one instance of Logger otherwise the log file will be created with every instance. In this case, we use the Singleton pattern and instantiate the logger when the first request comes or when the server is started.
  • There's a static LogManager.getLogManager() method, and a single global instance is used. In fact, this isn't a true singleton as you can derive your own class from LogManager and create extra instances that way - but it's typically used as a singleton.
  • Singleton pattern can be used for configuration files because it has a performance benefit as it prevents multiple users from repeatedly accessing and reading the configuration file or properties file. It creates a single instance of the configuration file which can be accessed by multiple calls concurrently as it will provide static config data loaded into in-memory objects. The application only reads from the configuration file for the first time and thereafter from the second call onwards the client applications read the data from in-memory objects. 
  • We can use the cache as a singleton object as it can have a global point of reference and for all future calls to the cache object the client application will use the in-memory object.

Mention what is the limitation of using singleton pattern?

The singleton pattern ensures that a class has only one instance and provides a global point of access to it. But at the same time this becomes its limitation as most classes in an application you will need to create multiple instances.

What are the drawbacks of using a singleton design pattern?

  • Singleton causes code to be tightly coupled. The singleton object is exposed globally and is available to a whole application. Thus, classes using this object become tightly coupled; any change in the global object will impact all other classes using it.
  • It hides the dependencies instead of exposing them.
  • Singleton Pattern does not support inheritance.
  • Singleton principle can be violated by techniques such as cloning. If an application is running on multiple JVM’s, then, in this case, Singleton might be broken.
In Part 3 of Java Design Pattern Interview Questions & Answers, I have explained Factory and Abstract Factory.

If you enjoy our content and want to support us, please consider donating via gpay, phonepay or paytm on +91 9920600280. Also, I’d appreciate it if you’d buy me a coffee☕ 

https://www.buymeacoffee.com/greekykhs


Keep learning and growing!
-K Himaanshu Shuklaa..

No comments:

Post a Comment