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.
Can you write a Java code snippet?
Sure! Please check it out:
/** © 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;
}
}
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.
- Let the constructor be private;
- 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.
- 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;
}
}
Hey my friend!
ReplyDeleteIn 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.
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.
ReplyDeleteTo 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!