public class SimpleSingleton {
private static SimpleSingleton INSTANCE = new SimpleSingleton();
//Marking default constructor private
//to avoid direct instantiation.
private SimpleSingleton() {
}
//Get instance for class SimpleSingleton
public static SimpleSingleton getInstance() {
return INSTANCE;
}
}
Code language: Java (java)
In above code snippet, we have declared a static object reference to SimpleSingleton class called INSTANCE and is returned every time getInstance() is called. In this design, the object will be instantiate when the class will be loaded and before the method getInstance() is being called. Demand loading (lazy loading) also called initialization on demand holder idiom is not seen in this implementation. We can change this code to add lazy init (Instantiate only when first time getInstance() is called) into this. Following is the code snippet for that. public class SimpleSingleton {
private SimpleSingleton singleInstance = null;
//Marking default constructor private
//to avoid direct instantiation.
private SimpleSingleton() {
}
//Get instance for class SimpleSingleton
public static SimpleSingleton getInstance() {
if(null == singleInstance) {
singleInstance = new SimpleSingleton();
}
return singleInstance;
}
}
Code language: Java (java)
public static synchronized SimpleSingleton getInstance() { }
Code language: Java (java)
clone()
method of the object. Hence it is advisable to overload clone() method of Object class and throw CloneNotSupportedException exception. public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
Code language: Java (java)
The Singleton pattern is widely used and has proved its usability in designing software. Although the pattern is not specific to Java, it has become a classic in Java programming. Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
Singletons lead to hard to test systems. Read the following post and similar post by Misko Hevery for some insight?
http://misko.hevery.com/2008/08/25/root-cause-of-singletons/
is it advisable to inherit a SingleTon Class..?
yes Himanshu, you can inherit the singleton class because the class is public. if it is final you cannot inherit any classes ok.
Thanking you.
This can be inherited but then the accessibilty of constructor should be made protected.And if we make the constructor protected then class can be extended by other class.
But by making the constructor protected the singleton design is lost.
Hi Himanshu,
I believe singleton design pattern doesn't disallow inheritance. Singleton guarantees single instance of a type and since derived class *is* its base type then inheritance is allowed as long as there is only one instance of the base (singleton) type. In other words only
one instance of the singleton class or any of its derived classes can exist.
Hi
I am trying to draw a singleton class diagram but do not understand uml too well. The singleton is to serve/ collaborate with a couple of other classes. Do I draw these other two classes next to the singleton class (and point an arrow towards each)?
I'm a bit confused.
Thanks for your help.
Hi,
Small correction needed in the given example. The non-static variable can not be used in the static context.
how i write singleton class is run.
can one singleton class inherit other singleton class?
Hello Perna!
do you mean can a singleton class can be inherit or not?
yes Perna. you can inherit the singleton class because it is public ok.
if it is final you cannot inherit the singleton class ok.
Thanking you.
No it ll not
[code language="java"]
public class SimpleSingleton {
private final SimpleSingleton singleInstance = null;
//Marking default constructor private
//to avoid direct instantiation.
private SimpleSingleton() {
}
//Get instance for class SimpleSingleton
public static synchronized SimpleSingleton getInstance() {
if(null == singleInstance) {
singleInstance = new SimpleSingleton();
}
return singleInstance;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
[/code]
That is an inferior singleton due to the overhead of the get instance synchronisation. People used to use double checked locking to avoid the synchronisation issue but that never worked due to the java memory model, double checked locking was apparently fixed in java 1.5 but who cares?
Singletons are generally considered an antipattern these days as sud mentioned, they result in hard to test code. We all use Dependency Injection nowadays and let the container control our object creation right?
Here is a quick piece of career advice... next time you are in a job interview and they ask about design patterns: don't mention Singleton! talk about Inversion Of Control or instead!
Nice post. I had recently posted about about implementing Singleton using C#. It might be helpful for those who know both Java and C# or are interested in both the languages.
http://www.nileshgule.com/2012/03/singleton-design-pattern.html
This design pattern is used for controlling the number of instances of a class (to one in general). This is maybe the first, the most used and the easiest design pattern out there.
Beware that this control ( controlling the number of instances of a class ) is available per classloader, and not for JVM, not to say more when thinking at distributed topologies. This is because the final static instance variable – being static is per class basis. As you know now, in a JVM you can have more than one classloader – meaning you can load the same Singleton implementing class more than once (once per classloader). Loading more than once the Singleton implementing class results in the possibility of having n instances controlled by the singleton per JVM, where n represents the number of the loads of the Singleton implementing class, so will need at least n classloaders.
In a multiple JVM topology ( cluster deployed application ) special algorithms must be taken into consideration for controlling the number of instances of a class. These can be fine-tuned depending on the needs of the application requirements.
The Singleton design pattern can also be expressed as an eager implementation which is thread safe too. Using synchronized you can make it thread safe without the eager initialization.
More at:
http://centraladvisor.com/programming-2/design-patterns/what-is-singleton-pattern
B/