Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!
A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.
There are only two points in the definition of a singleton design pattern,
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]”.
The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.
We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton instance.
package com.javapapers.sample.designpattern; public class Singleton { private static Singleton singleInstance; private Singleton() {} public static Singleton getSingleInstance() { if (singleInstance == null) { synchronized (Singleton.class) { if (singleInstance == null) { singleInstance = new Singleton(); } } } return singleInstance; }
You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.
The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.
package com.javapapers.sample.designpattern; public class Singleton { private static Singleton singleInstance = new Singleton(); private Singleton() {} public static Singleton getSingleInstance() { return singleInstance; } }
Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
This article is an attempt to explain the basics on singleton design pattern. If you want more insight on singleton refer this technical article “When is a Singleton not a Singleton?” and its references.
java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()
Comments are closed for "Singleton Design Pattern".
+1 for
synchronized (Singleton.class)
Listing 6
// Double-checked locking — don’t use
public static MySingleton getInstance() {
if (_instance==null) {
synchronized (MySingleton.class) {
if (_instance==null) {
_instance = new MySingleton();
}
}
}
}
In this situation, we intend to avoid the expense of grabbing the lock of the Singleton class every time the method is called. The lock is grabbed only if the Singleton instance does not exist, and then the existence of the instance is checked again in case another thread passed the first check an instant before the current thread.
Which one is better and why?
public static Singleton getSingleInstance() {
if (singleInstance == null) {
synchronized (Singleton.class) {
if (singleInstance == null) {
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
OR
public static synchronized Singleton getSingleInstance() {
if (singleInstance == null) {
singleInstance = new Singleton();
}
return singleInstance;
}
Unfortunately, double-checked locking causes problems. To wit, compiler optimizations can make the assignment of the new Singleton object before all its fields are initialized. (See “Double-checked locking is broken” in Resources.) The only practical solution is to synchronize the getInstance() method (as in Listing 2).
+1
Singleton was my first pattern too, but I remember it was also my first anti-pattern.
Beginners often miss the parts about good use, bad use and overuse, and about unit testing as well.
Hi first of all would like to say good article..I have few doubts
1)Isn’t it necessary to use volatile while dealing with threads
like it should be
private volatile static Singleton singleInstance;
2)I still didn’t understand wat is the reason behind checking for instance==null twice?
It would be of great help if you clear my doubts..
Regards,
Juned S
Good explanation of singleton design pattern. But even after doing this all, I can still create multiple instances of this class using clone() method from Object class.
public Object clone() throws CloneNotSupportedException {}
So one needs to overwrite this method in following way.
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
For me the simplest Singlton pattern is
enum Singleton {
INSTANCE;
}
I wouldn’t use make it more complex unless there is a good reason to do so.
very well explained.
also plz visit : http://techguru.yakkoo.com
where i tried to explain it in my own words
keep sharing the knowledge
Singleton could be sometimes useful.
Very nice explanation.
Instance can created by using dynamic class loading also .Singleton pattern can fail in that case. see my example in the below
—————————————————
Class.forName(“org.sri.design.ptrn.singleton.Singleton”);
Singleton instance3 = (Singleton)classSingleton.newInstance();
——————————————-
package org.sri.design.ptrn.singleton;
import org.sri.corejava.basic.Jeep;
public class Singleton {
private static Singleton singleInstance;
private Singleton(){
}
public static Singleton getSingleInstance(){
if(singleInstance == null){
synchronized(Singleton.class){
if(singleInstance == null){
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
public static void main(String args[]){
Singleton instance1 = Singleton.getSingleInstance();
System.out.println(“Instance Id=”+instance1.toString());
Singleton instance2 = Singleton.getSingleInstance();
System.out.println(“Instance Id=”+instance2.toString());
//dynamic class loading
Class classSingleton;
try {
classSingleton = Class.forName(“org.sri.design.ptrn.singleton.Singleton”);
Singleton instance3 = (Singleton)classSingleton.newInstance();
System.out.println(“Instance Id=”+instance3.toString());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InstantiationException ie){
ie.printStackTrace();
}
catch(IllegalAccessException iae){
iae.printStackTrace();
}
}
}
To avoid dynamic class loader problem don’t use default constructor
private Singleton(int arg){
}
private Singleton(){
if(singleInstance!= null){
throw new Error(“Don’t want any more instances”);
}
}
add above code to singleton instance creation to avoid Reflections
In the link referenced above it is said not to use synchronized on a block, instead use it on a method –
“Multiple instances can be created even if you add a synchronized(this) block to the constructor call, as in Listing 4:”. Can you shed more light on this please ?
Good Tutorial. But I think clonable must be implemented with throwing the clon not supported exception.
gud afnoon sir.
some people ask for using instance block at the time of class loading we can create object of a particular class so where we want that particular class we can instatiated that particular object by using static block then wt is the necessary to use it…
Hey..Joe..
Ur articles are intrseting..I started reading ur java articles..u r explaining in a simple way such a typical topics..thanks a lot..
Joe,
I think you must override the clone() method in the Singleton class to avoid the cloning..
According to Josh Bloch, use an enum instead: (like Peter Lawrey said above)
public enum YourSingleton {
INSTANCE;
public void doStuff(String stuff) {
System.out.println(“Doing ” + stuff);
}
}
@Dean, This is a java specific solution. Off course there can be different flavours of creating a singleton depending on the programming language you choose. But intention here is to understand the concept well and implement it in your own favourite language without any loophole.
and also avoid the taking high memory operation ra reduced or not
Thanks joe
Its really very useful to me. Thanks JOE
I agree with Peter Lawrey.
This is very clear to me. Thank you JOE.
How does the Early instantiation takes care of multithreading here? I dont understand. Please help.
Wouldn’t it be better if static function returning instance would be
public static singleTon getSingletonIns() {
synchronized (singleTon.class) {
if (singletonInstance == null) {
return new singleTon();
}
}
return singletonInstance;
}
as there seems no use of outer comparison.?
Want to add one point “we have to Override the Object clone method to prevent cloning”
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
Singleton design pattern is not so much easy to implement, still Joe has made it easier in Definition, and yes singleton is used in those project which are having some concentric Rules for Business and might have access those rules globally as per requirement…ri8???
I really appreciate your efforts in making design patterns express in such simple way. However I have a question on the following code snippet.
======================================
package com.javapapers.sample.designpattern;
public class Singleton {
private static Singleton singleInstance;
private Singleton() {}
public static Singleton getSingleInstance() {
if (singleInstance == null) {
synchronized (Singleton.class) {
if (singleInstance == null) {
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
=================================
I see a vulnerability here. If there is a non static member in this class it will be important to declare singleInstance as volatile. The reason is that without that there could be ordering defect because of which some thread(s) may see the non static member as uninitialized(null) even after they are initialized.
Cloning not hadled
Sometimes we have to modify a class that can’t be modified easily. Perhaps you need the source code and don’t have it (as may be the case with a commercial 3rd party class library). Or maybe any change would require modifying lots of existing subclasses. Design patterns offer ways to modify classes in such circumstances.
Which design pattern fits the above description
some may be use cloning in singleton pattern why?……..
nice explnation sir, iwant to know wher it is actually used at real time
nice explnation sir, iwant to know wher it is actually used at real time
Every single page in this blog is helpful :)
good one
nice to read
very much informative ..
How we design Singleton pattern in distributed environment. What stratigies we need to follow
Hi Joe, I wrote below code.
My question is shouldn’t compiler throw me an error while i try to instantiate 2nd object (SingletonPattern sp2 = new SingletonPattern();
) of SingletonPattern class.
I thought thats the objective of Singleton Pattern , to create only one instance .
public final class SingletonPattern {
private static SingletonPattern _instance;
private SingletonPattern(){
}
public static SingletonPattern getInstance()
{
if(_instance ==null)
{
_instance = new SingletonPattern();
System.out.println(“new Instance created.._instance= “+ _instance);
}
return _instance;
}
public static void main(String args[]){
SingletonPattern sp1 = new SingletonPattern();
SingletonPattern sp2 = new SingletonPattern();
}
}
Hi Joe,
How do we design Singleton pattern in distributed environment. What stratigies we need to follow..?
hi joe anna,
I have a query on what you have mentioned here “Factory design pattern can be used to create the singleton instance.”.
Actually factory design pattern is that “To create an object from one among the subtype”. Then how will that statement true?
Could you please explain or correct me if i am wrong?
What is the necessetity of overriding in the following scenario…
class Singleton {
private static Singleton singletonObject;
private Singleton() {}
public static synchronized Singleton getSingletonObject() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
public class SingletonObjectDemo {
public static void main(String args[]) {
Singleton obj = Singleton.getSingletonObject();
System.out.println(“Singleton object :” + obj);
}
}
Hi Joe,
The clone() method is protected in Object class. My doubt is If I didn’t override that method in Singleton class[below examle], still my class “Singleton” is singleton as we can’t call write obj.clone() in SingletonObjectDemo class?
what is the necessity of overriding the clone() method ?
class Singleton {
private static Singleton singletonObject;
private Singleton() {}
public static synchronized Singleton getSingletonObject() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
public class SingletonObjectDemo {
public static void main(String args[]) {
Singleton obj = Singleton.getSingletonObject();
System.out.println(“Singleton object :” + obj);
}
}
Very god one . thanks a lot
but sir by using reflection it can access the private data also by grant the policies of instaler file.
[…] is the default scope. Singleton design pattern requires no introduction as it is the easiest of all to understand. In the bean definition if the […]
Thank you for this article.
Gr8 blog……..thanks…:)
hi, its singleton when using check with clone() method, but how can we get same hashCode when run this application many times.
much obliged to you
Santosh Srivastava
1st one is better
we would like to see more real life examples and more comparisons with other design patterns.
thanks
You cannot create a new instance using classObject.newInstance() method in the above example. You will get IllegalAccessException if you try to do that.
Thanks sir,
For any JAVA doubt i only follow your blogs..
why do you need main method in singleton kumar. remove it.
Nice Article…Thank you for the information.
Thanks!!
Welcome Shashank.
“synchronized (Singleton.class) ” is for multiple threading environment i guess.. but i am not able to understand the parameter passed here “Singleton.class”, can you explain joe ?
Hi,
In the early initialization method you have expained:
package com.javapapers.sample.designpattern;
public class Singleton {
private static Singleton singleInstance = new Singleton();
private Singleton() {}
public static Singleton getSingleInstance() {
return singleInstance;
}
}
But I would suggest just directly define it in the following way:
package com.javapapers.sample.designpattern;
public class Singleton {
public static final Singleton singleInstance = new Singleton();
private Singleton() {}
}
Now if any class want’s to access it, it can be very easily as (static variables can be accessed directly. final ensures it’s security i.e any other class can’t modify it.):
Singleton.singleInstance
Do you think if there is anything wrong in my way.
Thanks for your time and effort to put on Internet world. I really appreciate your patience on this.
Could you please explain or write-up on Strategy Design pattern – which is also very important?
can i call clone() method in singleton class.
if i clone then what will happen, can you please explain it.
can i call clone() method in singleton class.
if i call then what will happen, can you please explain it.
II just got out of an interview. The hiring manager is a a Sr. VP in banking. When I told him how the Spring session factory is a factory pattern and when we instantiate the beans/bean class in IoC container, we have a choice of either flag the bean as singleton/prototype pattern. He was unable to accept it. I gave example of Payment-gateway instance as singleton and he was not convinced. Why some architects think that Singleton does not go together with other patterns?
Thanksss
link given for “When is a Singleton not a Singleton?” is broken!
http://www.oracle.com/technetwork/articles/java/singleton-1577166.html
Thanxs for clearing my ideas about Singleton design pattern.
Kumar, since you ae creating the instance in the Singleton main class. The private constuctor is accessible. So that is why it is creating the second instance.
Please change the background colour of “Creational Design Patterns, Structural Design Patterns, Behavioural Design Patterns” :)
instead of creating singleton if we do like this what will happen?
“if we create object for class and after using that object if we assign Null to that object” and again create obj and after completing usage of that again assign null to it”.
[…] design pattern and singleton design pattern is used in implementing the […]
Hello, your tutorials are great. Can`t we singleton with static variable with check too? I mean, I want to put only one instance in a hashmap of let`s say MongoClient class, but I could`t do it with your code, so I came up with other sollution:
private final static Map conn =
new HashMap ();
private static int instances = 0;
public static void newConn(String host, int port) {
if ( instances > 1 ) {
System.err.println(“Only one instance allowed”);
return;
} else {
try {
instances++;
conn.put(host, new MongoClient(host, port));
} catch (UnknownHostException e) { e.printStackTrace(); }
}
}
It worked for me creating only one instance and reference it by string… kind of what I needed. But don`t know about syncrho issues… Is it thread safe? Or must I add increment function (synchro) and volatile static variable?
1st one is better solution because it is having lock on object as well as It is checking for instance then only try to capture Object lock (synchronized) while in second method it self is synchronized means it will take lock first then check if object is present or not. This will lead to slow performance – think of case when you have 1000s of object request coming- each one has to wait for lock before getting object while in first method every request gets object without acquiring lock.
Hope this will help.
Ya its very helpfull…
good doc
Very good explanation
Thanks
hi sir,
how to use singleton pattern to open and close jdbc connection in java using oracle as backend
Good explanation…! Sir
The above one, as it does double check before creating the singleton instance.
COnsider there are 2 threads ,and both will reach before synchronized block .one of thread will enter and will check whether any instance is created or not,if there is no instance then it will create one .Once the thread one is done with the work it will release the lock,now thread 2 will enter in the synchronized block again it check whether any instance is already there or not ,it will get the earlier instance and will not create a new one.
Reflection will definitely break Singleton pattern. That is why readResolve() will come in picture.
good explanation Joe ,i am fan of your teaching style
Very helpful…Keep blogging !
in a real time projects where exactly used single tone class tell me one project example
please anyone explain that what does mean by –
synchronized(Singleton.class)
I know about synchronized method and synchronized block. But i’m not able to understand the above usage of synchronization.
please someone explain. Thanks !!
Hi Joe,
This is really very simple & nice explanation.
Many thanks!
Good job. It’s very clear.
“It also takes care of the multithreading scenario.”
I wonder that the static field was initialized thread safely when class loaded or not. And I heard that a static field would be initialized only once. If so, is it necessary to take multithread into account?
[…] Proxy design pattern gets second rank in popularity in interviews. Guess who gets the first rank? none other than singleton design pattern. […]
Cloning the object can still copy it and result into duplicate object.if i overload clone method than it’s compulsory to implements cloneable interface.
Hi Joe,
This is really very simple & nice explanation.
Thanks
Fareed
I think the second one as it contains less code…easy to summaries :D
I think , the Singleton class will load at the starting of the program execution also the singleInstance as it is a static veriable. So there will not be any situation where that variable will be different.
First one is better.
Consider the multithreading scenario. The second method will always make other threads wait until one thread is executing it, regardless of a instance is already created or not.
The first method will block other threads only once in the scenario where instance is not created yet. Once the instance is created, the synchronised block will never needed to be entered. Hence increasing the efficiency.
Nice Effort you did a great job…
Hi
Its really nice article to learn about singleton pattern. i have a question that, is singleton pattern does have strict control over how and when client access it. I understand after read this article that it will have strict control on how client access the singleton object. But i m still confused on control on when client access singleton object, i think it can have control only in case singleton class is synchronized, and we can create singleton object without synchronization also if your application is single threaded environment. plz clarify
Thanks Joe for such nice text…
Here is an article on same topic
“How to design Singleton Pattern using Java?
Posted on February 10, 2014 by admin
Singleton pattern is one most commonly used pattern in every types of software application developments. Therefore every interviewer would like to ask about this pattern first. This is really simple design pattern to create but you need to take care of some common things to design this pattern. Before going deep, let us concentrate on singleton pattern definition.”
Every class in Java has an associated instance of java.lang.Class that contains metadata about the class–its field names and types, method declarations, parent class, etc. When you see ClassName.class that is known as a class literal. It is a compile-time constant that evaluates to a reference to that class’s Class object.
I would like to ask a question about your example which is below:
package com.javapapers.sample.designpattern;
public class Singleton {
private static Singleton singleInstance;
private Singleton() {}
public static Singleton getSingleInstance() {
if (singleInstance == null) {
synchronized (Singleton.class) {
if (singleInstance == null) {
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
Q> why we want outer if() block when we are checking inside the synchronized block ?
The explanation is very nice and clear . It would be more better if you give an example of Multi-threading with Singleton (both Early and lazy instantiation ).Then I think it will be a complete article for Singleton.
u can assign the value as null but there is a reference created for that object i mean some address is stored for that specific object so if you assign null and try to create a another object it will not create a new object even you can test it by printing the address of the object.
Sound good..
Always use method with Synchronized block. Second one contains only few lines of code but one issue with that is if two threads access the simultaneously both will initialize the object. To avoid this synchronization is used.
Always better to practice with use synchronized part in Singleton classes.
1 st one is better and it is perfomance wise it’s good.why?because
if u are unnecessary acquiring the lock, if object is already there if u can return use this.why it is entire method is acquries a lock.
this is perfomance issue.
first one object is created,next one is entered it unnecessary to acquires the lock entire method……..
so second one is gives a small perfomance issue
Your way of explanation is very simple and easy to understand for beginners as well as intermediate developers.
Thanks for such a wonderful blog.
Could you write about all Design Principles in Java like DRY (Don’t Repeat Yourself), Single Responsibility Principle.
Also it would be helpful if there was an Android app for this website.
Thanks Ashok.
Both are in queue. I trying to cover all design patterns one by one. The mobile app for Javapapers will be launched soon.