Thursday, March 29, 2012

What is the Singleton design pattern?

What is the Singleton design pattern?
The Singleton pattern is used when you want to have only a single instance of a class in a running system.


How to implement the Singleton design pattern in Java?
There are many different ways to implement it. I will just show a simple one, that doesn't handle multi-threaded access. 
  1. Let the constructor be private;
  2. Write a public static method to return the single instance (a.k.a. "singleton"). This method checks if this is the first time the method is being called. In case positive, it creates the singleton, stores it and returns it; otherwise, it just returns the previously stored instance.
  3. Define a way to store the singleton. It could be a static variable.


Can you write a Java code snippet?
 Sure! Please check it out:

Java code snippet: Singleton design pattern

/** © 2012 interviewqa4java.blogspot.com */
public class
Singleton {

    private static
Singleton singleton = null;

    private
Singleton() {
    }

    public static Singleton getSINGLETON() {
        if
(singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    
}
}

2 comments:

  1. Hey my friend!
    In a concurrent environment, several threads may call the getSingleton method. In this scenario, it could be possible for one thread to get suspended after the "if" and before the allocation, and another thread runs, getting in the "if" and allocating the singleton variable. The suspended thread runs again and ends up overwriting the singleton variable. I do think your idea was to make it simple for the sake of understanding the concept behind this pattern. As a further study, you might want to elaborate on how to avoid the problem I just explained. Keep up the good work.

    ReplyDelete
  2. You're right, Carlos, there are other different ways to implement the Singleton pattern in Java and here I just showed a simple one, that doesn't handle multi-threaded access.

    To handle this case, please take a look at the post "What is the meaning of the keyword Synchronized?"

    One possible solution would be putting the if clause within the synchronized block:

    //...
    synchronized(this){
    if (singleton == null) {
    singleton = new Singleton();
    }
    }
    In this case the if will only run on the 1st time a thread calls the getINSTANCE() method.

    I haven't tested this solution (I have to go to work now), so please let me know if there is something to improve here.

    Thanks for the comment and for the feedback!

    ReplyDelete

Please, before starting to comment, evaluate if what you want to write is useful, respectful and positive. A kid may read this also.

Give a good example!