Saturday, January 5, 2013

Singleton Design Pattern

The Singleton is a useful Design Pattern for allowing only one instance of your class, but common mistakes can inadvertently allow more than one instance to be created. 

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time. If you add database connections or use a JDBC driver that allows multithreading, the Singleton can be easily adjusted to allow more connections.

Implementing Singletons

There are a few ways to implement Singletons. Although you can get Singleton-like behavior with static fields and methods [for example, java.lang.Math.sin(double)], you gain more flexibility by creating an instance. With Singletons implemented as single instances instead of static class members, you can initialize the Singleton lazily, creating it only when it is first used. Likewise, with a Singleton implemented as single instance, you leave open the possibility of altering the class to create more instances in the future. With some implementations of the Singleton, you allow writers of subclasses to override methods polymorphically, something not possible with static methods.

Most commonly, we can implement a Singleton in Java by having a single instance of the class as a static field. We can create that instance at class-loading time by assigning a newly created object to the static field in the field declaration, as seen in Listing 1.

Listing 1

public class MySingleton {
 private static MySingleton _instance =
  new MySingleton();

 private MySingleton() {
  // construct object . . .
 }

 public static MySingleton getInstance() {
  return _instance;
 }

 // Reminder of class definition . . .
Alternatively, you can instantiate it lazily, on first demand, as seen in Listing 2. You keep the constructor private to prevent instantiation by outside callers.

Listing 2

public class MySingleton {
 private static MySingleton _instance;

 private MySingleton() {
  // construct object . . .
 }

 // For lazy initialization
 public static synchronized MySingleton getInstance() {
  if (_instance==null) {
   _instance = new MySingleton();
  }
  return _instance;
 }
  // Remainder of class definition . . .
}
Both Singleton implementations do not allow convenient subclassing, since getInstance(), being static, cannot be overridden polymorphically.

Below are some interesting Singleton Design pattern faqs. Courtesy of javarevisited.blogspot.com

What is Singleton class? Have you used Singleton before?
Singleton is a class which has only one instance in whole application and provides a getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.

1) Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?
Answer: Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class , since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application, if you want to show popup with message you can have one PopUp class on whole GUI application and anytime just get its instance, and call show() with message.

2) Can you write code for getInstance() method of a Singleton class in Java?
Answer: Until asked don’t write code using double checked locking as it is more complex and chances of errors are more but if you have deep knowledge of double checked locking, volatile variable and lazy loading than this is your chance to shine.

3) Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer?
Answer: This is again related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to getInstance() will be synchronized and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton,  It’s better to only synchronize critical section and not whole method. Singleton patternis also closely related to factory design pattern where getInstance() serves as static factory method.

4) What is lazy and early loading of Singleton and how will you implement it?
Answer: As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.


5) Example of Singleton in standard Java Development Kit?
This is open question to all, please share which classes are Singleton in JDK. Answer to this question is java.lang.Runtime
Answer: There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:

  • Java.lang.Runtime with getRuntime() method
  • Java.awt.Toolkit with getDefaultToolkit()
  • Java.awt.Desktop with  getDesktop()

6) What is double checked locking in Singleton?
Answer: Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization.

public Singleton getInstance(){
    if(_INSTANCE == null){
        synchronized(Singleton.class){
        //double checked locking - because second check of Singleton instance with lock
               if(_INSTANCE == null){
                   _INSTANCE = new Singleton();
               }
           }
        }
    return _INSTANCE;
}

Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.

7) How do you prevent for creating another instance of Singleton using clone() method?
Answer: Preferred way is not to implement Clonnable interface as why should one wants to create clone() of Singleto and if you do just throw Exception from clone() method as  “Can not create clone of Singleton class”.

8) How do you prevent for creating another instance of Singleton using reflection?
Open to all. In my opinion throwing exception from constructor is an option.
Answer: This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”

9) How do you prevent for creating another instance of Singleton during serialization?
Another great question which requires knowledge of Serialization in Java and how to use it for persisting Singleton classes. This is open to you all but in my opinion use of readResolve() method can sort this out for you.
Answer: You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance.

10) When is Singleton not a Singleton in Java?
There is a very good article present in Sun's Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible.

11) Why you should avoid the singleton anti-pattern at all and replace it with DI?
Answer: Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container.

Singleton Anti-Pattern: with more and more classes calling getInstance the code gets more and more tightly coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden dependencies. Also, there would be no need for this clumsy double checked locking if you call getInstance less often (i.e. once).

12) How many ways you can write Singleton Class in Java?
Answer:  I know atleast four ways to implement Singleton pattern in Java
1) Singleton by synchronizing getInstance() method
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums

13) How to write thread-safe Singleton in Java?
Answer: Thread-Saffe Singleton usually refers to write thread safe code which creates one and only one instance of Singleton if called by multiple thread at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using Enum or Singleton initialized by classloader.

1 comment:

  1. Well explained . Great article on singleton pattern . There is also good singleton pattern example visit Singleton class example

    ReplyDelete