I have developed singleton in many ways depending upon the condition like volatile/lazy singleton, eager singleton, normal singleton and through Enum also, but specifically I want to know about static holder pattern singleton shown below.
public static class Singleton {
private static class InstanceHolder {
public static Singleton instance = new Singleton();
}
private Singleton(){}
public static Singleton getInstance() {
return InstanceHolder.instance;
}
}
Please advise under which conditions it is beneficial and what are its benefits.
This pattern is beneficial for at least 3 reasons:
Static factory
Lazy initialization
Thread safe
The JVM defers initializing the InstanceHolder class until it is actually used, and because the Singleton is initialized with a static initializer, no additional synchronization is needed. The first call to getInstance by any thread causes InstanceHolder to be loaded and initialized, at which time the initialization of the Singleton happens through the static initializer.
Static holder pattern is also considered as the smartest replace for Double-check-locking antipattern.
This is a way to make a thread-safe lazy singleton by exploiting the way how JVM loads classes. You can read more about why and how to correctly implement it in Bloch's Effective Java book.
Remember, that from the testable code point of view singletons (and global state in general) are not beneficial and should be avoided.
Related
I am learning singleton design pattern from the head first design pattern book.
They have given one approach which uses static initialization. Static initialization is done at the time of class loading and the problem with this approach is that it will create the instance even if we are not using it(at the time of class loading) which means it will do eager initialization.
public enum Singleton {
private static Singleton uniqueInstance = new Singleton();
// Other useful fields here (can be static or non-static)
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
// Other useful methods here (can be static or non-static)
}
They have given one more approach which uses an enum.
public enum Singleton {
UNIQUE_INSTANCE;
// other useful fields here (can be static or non-static)
public static Singleton getInstance() {
return UNIQUE_INSTANCE;
}
// other useful methods here (can be static or non-static)
}
I want to know what is the difference between the above approaches in terms of when the object is created(In both cases when we are using that object in the application and when we are not using the object throughout the application).
In other words, I want to know whether the enum approach will also do eager initialization?
When using an enum, the single constant is public. There's no need to add a getter for it.
As far as I'm concerned, only use an enum if you need any of its advantages. There aren't that many though, since comparison and switching is not relevant with only a single instance. There is one advantage I can think of (if you need it): enums are serializable. Getting serialization to work for non-enum singletons isn't trivial; you need to work with readResolve (and possibly writeReplace) to make sure that when the serialized singleton value is read from the steam, no new instance is returned. One is still created though, it will just be discarded. When using an enum you get serialization for free.
👉 Enum objects are instantiated when the enum class loads.
So yes, you could consider that to be "eager initialization".
Using an enum to define a Singleton in Java is the approach recommended by Dr. Joshua Bloch in his famous book, Effective Java.
Is the Initialize-On-Demand idiom really necessary when implementing a thread safe singleton using static initialization, or would a simple static declaration of the instance suffice?
Simple declaration of instance as static field:
class Singleton
{
private static Singleton instance=new Singleton();
private Singleton () {..}
public static Singleton getInstance()
{
return instance;
}
}
vs
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
private Singleton () {..}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
I ask this because Brian Goetz recommends the 1st approach in this article:
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
while he suggests the latter in this article
http://www.ibm.com/developerworks/library/j-jtp03304/
Does the latter approach provide any benefits that the former doesn't?
Well what i can say These articles are 7-9 years old.
Now we have > Java 1.5 where we have power of enumeration enum. According to 'Josh Block' The best way to write a singleton is to write a Single Element enum
public enum MySingleton{
Singleton;
// rest of the implementation.
// ....
}
But for your question I guess there is no issue in using either of the implementations. I personaly prefer the first option because its straightforward, simple to understand.
But watch out for the loop holes that we can be able to create more objects of these class in the same JVM at the same time by serializing and deserializing the object or by making the clone of the object.
Also make the class final, because we can violate the singleton by extending the class.
In first approach your singleton will get created once you load Singleton class. In the other, it will get created once you call getInstance() method. Singleton class may have many reasons to get loaded before you call getInstance. So you will most likely initialize it much earlier when you actually use it and that defeats the purpose of lazy initialization. Whether you need lazy initialization is a separate story.
The simple declaration pattern constructs the singleton when when the class Singleton is loaded. The initialize-on-demand idiom constructs the singleton when Singeton.getInstance() is called -- i.e., when class SingetonHolder is loaded.
So these are the same except for time; the second option allows you delay initialization. When to choose one or the other depends on (among other things) how much work you are doing in Singleton's constructor. If it's a lot, you may see improved application startup time with initialization-on-demand.
That said, my advice is to try not to do too much there so that the simplest pattern works for you.
-dg
I have 2 options:
Singleton Pattern
class Singleton{
private static Singleton singleton = null;
public static synchronized Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
using a static final field
private static final Singleton singleton = new Singleton();
public static Singleton getSingleton() {
return singleton;
}
Whats the difference? (singlethreaded or multithreaded)
Updates: I am aware of Bill Pugh or enum method.
I am not looking for the correct way, but I have only used 1. Is there really any difference b/w 1 or 2?
The main difference is that with the first option , the singleton will only be initialised when getInstance is called, whereas with the second option, it will get initialized as soon as the containing class is loaded.
A third (preferred) option which is lazy and thread safe is to use an enum:
public enum Singleton {
INSTANCE;
}
There is one difference:
Solution 1 is a lazy initialization, the singleton instance will be created on the first invoke of getInstance
Solution 2 is a eager initialization, the singleton instance will be create when the class loades
They both are thread safe, calling the second one multi threaded is a little misleading
The 1st solutions appears to be lazier, but actually not.
A class is initialized when a static method/field is accessed for the 1st time.
It's likely that getInstance() is the only publicly accessible static method/field of the class. That's the point of singleton.
Then the class is initialized when someone calls getInstance() for the 1st time. That means the two solutions are essentially the same in laziness.
Of course, the 2nd solutions looks better and performs better.
So, with the update both options above are thread-safe. However the synchronized option requires each thread that calls instance to acquire this lock thereby reducing performance if this is done a lot. Also, using synchronized at the method level has the potential issue of using a publicly available lock (the class itself) that therefore if some thread acquires this lock (which it could) you could end up with deadlock. The static final option is more performant but does not do lazy initialization of the singleton (which might not be an issue depending on the system).
Another option that allows thread-safe lazy init of the Singleton is as follows:
public class MySingleton{
private static class Builder{
private static final MySingleton instance = new MySingleton();
}
public static MySingleton instance(){
return Builder.intance;
}
}
This works because the static inner class is guarenteed to be initialized before any method in the containing class is executed.
The wikipedia article on Singletons mentions a few thread safe ways to implement the structure in Java. For my questions, let's consider Singletons that have lengthy initialization procedures and are acccessed by many threads at once.
Firstly, is this unmentioned method thread-safe, and if so, what does it synchronize on?
public class Singleton {
private Singleton instance;
private Singleton() {
//lots of initialization code
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Secondly, why is the following implementation thread safe AND lazy in initialization? What exactly happens if two threads enter the getInstance() method at the same time?
public class Singleton {
private Singleton() {
//lots of initialization code
}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
Finally, in the second example, what if one thread gets an instance first and another thread gets an instance and tries to perform actions on it before the constructor has finished in the first thread? Can you get into an unsafe state then?
Answer 1: static synchronized methods use the class object as the lock - ie in this case Singleton.class.
Answer 2: The java language, among other things:
loads classes when they are first accessed/used
guarantees that before access to a class is allowed, all static initializers have completed
These two facts mean that the inner static class SingletonHolder is not loaded until the getInstance() method is called. At that moment, and before the thread making the call is given access to it, the static instance of that class is instantiated as part of class loading.
This all means we have safe lazy loading, and without any need for synchronization/locks!
This pattern is the pattern to use for singletons. It beats other patterns because MyClass.getInstance() is the defacto industry standard for singletons - everyone who uses it automatically knows that they are dealing with a singleton (with code, it's always good to be obvious), so this pattern has the right API and the right implementation under the hood.
btw Bill Pugh's article is worth reading for completeness when understanding singleton patterns.
I am referring to the solution for the Singleton Pattern by Bill Pugh on Wikipedia:
public class Singleton
{
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder
{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance()
{
return SingletonHolder.INSTANCE;
}
}
Here they have mentioned:
The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).
However, isn't there a possibility that 2 threads would call getInstance() at the same time, which would lead to two instances of singleton being created? Isn't it safe to use synchronized here? If yes, where should it be used in the code?
See the "How it works", in the article "Initialization on demand holder idiom" linked from the same section.
In a nutshell, here's what happens when you call getInstance() the first time:
The JVM sees a reference to SingletonHolder it has never seen referenced before.
Execution is paused while it initializes SingletonHolder. This includes running any static initialization, which includes the singleton instance.
Execution resumes. Any other threads calling getInstance() at the same time will see that SingletonHolder is already initialized. The Java spec guarantees that class initialization is thread-safe.
The JLS guarantees the JVM will not initialize instance until someone calls getInstance(); and that will be thread safe because it would happen during the class initialization of SingletonHolder.
However, since Java 5, the preferred approach involves Enum:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
Reference: Implementing the singleton pattern in Java
Here is the explanation from Wikipedia on this phenomenon (emphasis mine):
When the class Something is loaded by
the JVM, the class goes through
initialization. Since the class does
not have any static variables to
initialize, the initialization
completes trivially. The static class
definition LazyHolder within it is not
initialized until the JVM determines
that LazyHolder must be executed. The
static class LazyHolder is only
executed when the static method
getInstance is invoked on the class
Something, and the first time this
happens the JVM will load and
initialize the LazyHolder class. The
initialization of the LazyHolder class
results in static variable something
being initialized by executing the
(private) constructor for the outer
class Something. Since the class
initialization phase is guaranteed by
the JLS to be serial, i.e.,
non-concurrent, no further
synchronization is required in the
static getInstance method during
loading and initialization. And since
the initialization phase writes the
static variable something in a serial
operation, all subsequent concurrent
invocations of the getInstance will
return the same correctly initialized
something without incurring any
additional synchronization overhead.
So in your example, Singleton is "LazyHolder" and SingletonHolder is "Something". Calling getInstance() twice will not cause a race condition due to the JLS guarantees.
I think the idea is that Java guarantees that a class can only be initialized once, so implicitly only the first thread to access would cause this to happen
The Singleton is created when Singleton.getInstance() is called at this time the INSTANCE will be instantiated.
Synchronization depends on a conrete implementation, since there are no values to modify (in this example) no synchronization is required.
There are two differences here that need to be noted. The first is the Singleton design pattern and the other is a singleton instance.
The Singleton design pattern is problematic due to the fact that the design pattern represents a singleton instance as is implemented using static state (which is a bad thing for a variety of reasons - especially with unit testing). The second is an instance for which there is only one instance, no matter what (like the JVM singleton implemented as an enum).
The enum version is definitely superior, when compared to the Singleton pattern.
If you don't want to implement all instances as enum instances, then you should think about using Dependency Injection (frameworks such as Google Guice) to manage the singleton instances for the application.
This idiom is known as the Initialization on Demand Holder (IODH) idiom and is discussed in Item 48 of Effective Java as reminded by Bob Lee in his great post about Lazy Loading Singletons:
Item 48: Synchronize access to shared mutable data
(...)
The initialize-on-demand holder
class idiom is appropriate for use
when a static field is expensive to
initialize and may not be needed, but
will be used intensively if it is
needed. This idiom is shown below:
// The initialize-on-demand holder class idiom
private static class FooHolder {
static final Foo foo = new Foo();
}
public static Foo getFoo() { return FooHolder.foo; }
The idiom takes advantage of the
guarantee that a class will not be
initialized until it is used [JLS,
12.4.1]. When the getFoo method is
invoked for the first time, it reads
the field FooHolder.foo, causing the
FooHolder class to get initialized.
The beauty of this idiom is that the
getFoo method is not synchronized
and performs only a field access, so
lazy initialization adds practically
nothing to the cost of access. The
only shortcoming of the idiom is that
it does not work for instance fields,
only for static fields.
However, in the Second Edition of Effective Java, Joshua explains how enums can be (ab)used for writing a serializable Singleton (this should be the preferred way with Java 5):
As of release 1.5, there is a third approach to implementing singletons. Simply
make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it
is more concise, provides the serialization machinery for free, and provides an
ironclad guarantee against multiple instantiation, even in the face of sophisticated
serialization or reflection attacks. While this approach has yet to be widely
adopted, a single-element enum type is the best way to implement a singleton.