An immutable object is initialized by its constuctor only, while a singleton is instantiated by a static method. How to make an immutable singleton in Java?
while a singleton is instantiated by a
static method
While this is the usual way of doing it, this is by no means the only way.
In Java 1.5 a new version of Singleton is the enum singleton pattern:
public enum Elvis{
INSTANCE // this is a singleton, no static methods involved
}
And since enums can have constructors, methods and fields, you can give them all the immutable state you want.
Reference:
Java tutorial: Enum Types
Effective Java, Item 3
Singleton (the enum way)
(WikiPedia)
Also, the term Singleton leaves some room for interpretation. Singleton means that there is exactly one object per defined scope, but the scope can be a number of things:
Java VM Classloader (thanks #Paŭlo Ebermann for reminding me): in this case use enums or the initialize-through-static-inner-class pattern. This is of course what is usually meant by a singleton.
Be Careful: enums and all other singletons are broken if loaded through multiple Classloaders.
Enterprise Application (in this case you need a container-managed singleton, e.g. a Spring singleton bean). This can be several objects per VM or one object per several VMs (or one Object per VM, of course)
Thread (use a ThreadLocal)
Request / Session (again, you'll need a container to manage this, Spring, Seam and several others can do that for you)
did I forget anything?
All of the above can be made immutable, each in their own way (although it's usually not easy for container-managed components)
The solution pointed out by Sean is a good way of initializing singletons if their creation is not expensive. If you want to "lazy loading" capability, look into the initialization on demand holder idiom.
// from wikipedia entry
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 {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
public enum MySingleton {
instance;
//methods
}
//usage
MySingleton.instance.someMethod();
You're being unnecessary complicated. To be immutable an object must be unmodifiable once it is created. That's normally interpreted to mean "modifiable only in the constructor", but if you were to create it another way that would still make it immutable. As long as your object cannot be modified after it is initialized then it is immutable. You can consider setting up the Singleton instance to be part of the initialization.
Most of the benefits of immutability are irrelevant in Singletons.
Related
I have a stateless helper-like class which I want to make as a singleton. This class will be shared across different threads.
Am I correct that in this case (instance does not require huge memory allocation size and thus can be loaded several times without resources and performance impact) there is no need in implementing such a singleton with proper multi-threading lazy initialization strategy (Double Checked Locking & volatile, On Demand Holder idiom, Enum Singleton, Synchronized Accessor)?
Is it right to implement such a singleton with a simple non-multi-threading lazy initialization version strategy (like in the code below) in order to have less amount of boilerplate code?
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
And only in case when state of the singleton class shared across different threads it is required to add proper multi-threading version of a singleton initialization?
If your class is entirely stateless - make it a util class with only static functions.
If you have state and want a semi-singleton I would say that what you have done is misleading since there is no way for the reader to know if you were aware of the fact that you can get multiple instances or not. If you decide to stick with your posted code - rename it multiton or document the behaviour carefully. But don't do it just to reduce boilerplate though - you are in fact creating more problems for the reader than you are removing.
In my opinion the "Initialization on Demand Holder" idiom is the nicest singleton pattern. But I would recommend against Singletons in general. You would be better off passing a reference to a shared instance to your thread when you start it.
To answer your question... No, it's not correct.
You say it's OK for it to be loaded several times, but in that case then it's not a singleton. The defining characteristic of a singleton is that there can only ever be one instance.
If it's OK for there to be several, then why make it a singleton at all?
If it's just stateless util methods then why not just make the static?
I have read that it is possible to implement Singleton in Java using an Enum such as:
public enum MySingleton {
INSTANCE;
}
But, how does the above work? Specifically, an Object has to be instantiated. Here, how is MySingleton being instantiated? Who is doing new MySingleton()?
This,
public enum MySingleton {
INSTANCE;
}
has an implicit empty constructor. Make it explicit instead,
public enum MySingleton {
INSTANCE;
private MySingleton() {
System.out.println("Here");
}
}
If you then added another class with a main() method like
public static void main(String[] args) {
System.out.println(MySingleton.INSTANCE);
}
You would see
Here
INSTANCE
enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.
An enum type is a special type of class.
Your enum will actually be compiled to something like
public final class MySingleton {
public final static MySingleton INSTANCE = new MySingleton();
private MySingleton(){}
}
When your code first accesses INSTANCE, the class MySingleton will be loaded and initialized by the JVM. This process initializes the static field above once (lazily).
In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:
Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.
Recommended approach is implement Singletons by 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.
Like all enum instances, Java instantiates each object when the class is loaded, with some guarantee that it's instantiated exactly once per JVM. Think of the INSTANCE declaration as a public static final field: Java will instantiate the object the first time the class is referred to.
The instances are created during static initialization, which is defined in the Java Language Specification, section 12.4.
For what it's worth, Joshua Bloch describes this pattern in detail as item 3 of Effective Java Second Edition.
As has, to some extent, been mentioned before, an enum is a java class with the special condition that its definition must start with at least one "enum constant".
Apart from that, and that enums cant can't be extended or used to extend other classes, an enum is a class like any class and you use it by adding methods below the constant definitions:
public enum MySingleton {
INSTANCE;
public void doSomething() { ... }
public synchronized String getSomething() { return something; }
private String something;
}
You access the singleton's methods along these lines:
MySingleton.INSTANCE.doSomething();
String something = MySingleton.INSTANCE.getSomething();
The use of an enum, instead of a class, is, as has been mentioned in other answers, mostly about a thread-safe instantiation of the singleton and a guarantee that it will always only be one copy.
And, perhaps, most importantly, that this behavior is guaranteed by the JVM itself and the Java specification.
Here's a section from the Java specification on how multiple instances of an enum instance is prevented:
An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type. The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.
Worth noting is that after the instantiation any thread-safety concerns must be handled like in any other class with the synchronized keyword etc.
Since Singleton Pattern is about having a private constructor and calling some method to control the instantiations (like some getInstance), in Enums we already have an implicit private constructor.
I don't exactly know how the JVM or some container controls the instances of our Enums, but it seems it already use an implicit Singleton Pattern, the difference is we don't call a getInstance, we just call the Enum.
In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.
As a user, you shouldn't worry about it.
class Singelton
{
private static Singelton _singelton = null;
private Singelton()
{
}
// NOT usable for Multithreaded program
public static Singelton CreateMe()
{
if(_singelton == null)
_singelton = new Singelton();
return _singelton;
}
}
Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.
I would use an enum
enum Singleton {
INSTANCE:
}
or something similar which cannot be instantiated more than once and globally accessible.
General practice for naming methods which create/return singletons is getInstance(). I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.
If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling getInstance() method.
If your question is about reusing of created Singletons, then search this site. For example
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 had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can implement Singleton Design Patterns.
He seems to be half satisfied with the answer but I want to know
How many different ways we can
implement Singleton Design Pattern
in Java ?
What is the scope of Singleton Object and how does it actually work inside JVM ? I know we would always have one instance of Singleton Object but what is the actual scope of that object, is it in JVM or if there are multiple application running than it's scope is per context basis inside the JVM, I was really stumped at this and was unable to give satisfying explanation ?
Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
Any inputs would be highly appreciated about Singleton and what are the main things to keep in mind while dealing with Singletons ?
Thanks.
There are a few ways to implement a Singleton pattern in Java:
// private constructor, public static instance
// usage: Blah.INSTANCE.someMethod();
public class Blah {
public static final Blah INSTANCE = new Blah();
private Blah() {
}
// public methods
}
// private constructor, public instance method
// usage: Woo.getInstance().someMethod();
public class Woo {
private static final Woo INSTANCE = new Woo();
private Woo() {
}
public static Woo getInstance() {
return INSTANCE;
}
// public methods
}
// Java5+ single element enumeration (preferred approach)
// usage: Zing.INSTANCE.someMethod();
public enum Zing {
INSTANCE;
// public methods
}
Given the examples above, you will have a single instance per classloader.
Regarding using a singleton in a cluster...I'm not sure what the definition of "using" is...is the interviewer implying that a single instance is created across the cluster? I'm not sure if that makes a whole lot of sense...?
Lastly, defining a non-singleton object in spring is done simply via the attribute singleton="false".
I disagree with #irreputable.
The scope of a Singleton is its node in the Classloader tree. Its containing classloader, and any child classloaders can see the Singleton.
It's important to understand this concept of scope, especially in the application servers which have intricate Classloader hierarchies.
For example, if you have a library in a jar file on the system classpath of an app server, and that library uses a Singleton, that Singleton is going to (likely) be the same for every "app" deployed in to the app server. That may or may not be a good thing (depends on the library).
Classloaders are, IMHO, one of the most important concepts in Java and the JVM, and Singletons play right in to that, so I think it is important for a Java programmer to "care".
I find it hard to believe that so many answers missed the best standard practice for singletons - using Enums - this will give you a singleton whose scope is the class loader which is good enough for most purposes.
public enum Singleton { ONE_AND_ONLY_ONE ; ... members and other junk ... }
As for singletons at higher levels - perhaps I am being silly - but my inclination would be to distribute the JVM itself (and restrict the class loaders). Then the enum would be adequate to the job .
Singleton is commonly implemented by having a static instance object (private SingletonType SingletonType.instance) that is lazily instantiated via a static SingletonType SingletonType.getInstance() method. There are many pitfalls to using singletons, so many, in fact, that many consider singleton to be a design anti-pattern. Given the questions about Spring, the interviewer probably was looking for an understanding not only of singletons but also their pitfalls as well as a workaround for these pitfalls known as dependency injection. You may find the video on the Google Guice page particularly helpful in understanding the pitfalls of singletons and how DI addresses this.
3: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.
The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.
a static field can have multiple occurrences in one JVM - by using difference class loaders, the same class can be loaded and initialized multiple times, but each lives in isolation and JVM treat the result loaded classes as completely different classes.
I don't think a Java programmer should care, unless he's writing some frameworks. "One per VM" is a good enough answer. People often talk that way while strictly speaking they are saying "one per classloader".
Can we have one singleton per cluster? Well that's a game of concepts. I would not appreciate an interviewer word it that way.
There's the standard way, which you already covered. Also, most dependency-injection schemes have some way to mark a class as a singleton; this way, the class looks just like any other, but the framework makes sure that when you inject instances of that class, it's always the same instance.
That's where it gets hairy. For example, if the class is initialized inside a Tomcat application context, then the singleton instance's lifetime is bound to that context. But it can be hard to predict where your classes will be initialized; so it's best not to make any assumptions. If you want to absolutely make sure that there's exactly one instance per context, you should bind it as an attribute of the ServletContext. (Or let a dependency-injection framework take care of it.)
--
Not sure I understand the question - but if you're talking about having a singleton instance that's shared between several cluster nodes, then I think EJB makes this possible (by way of remote beans), though I've never tried it. No idea how Spring does it.
Singleton is a creational pattern and hence governs object instantiation. Creating singletons would mandate that you voluntarily or involuntarily give up control on creating the object and instead rely on some way of obtaining access to it.
This can be achieved using static methods or by dependency injection or using the factory pattern. The means is immaterial. In case of the normal protected constructor() approach, the consumer perforce needs to use the static method for accessing the singleton. In case of DI, the consumer voluntarily gives up control over the instantiation of the class and instead relies on a DI framework to inject the instance into itself.
As pointed out by other posters, the class loader in java would define the scope of the singleton. Singletons in clusters are usually "not single instances" but a collection of instances that exhibit similar behavior. These can be components in SOA.
The Following Code is from here
The Key point is you should Override the clone method...The Wikipedia example also is helpful.
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
private static SingletonObject ref;
}
Query 1:
Different ways of creating Singleton
Normal Singleton : static initialization
ENUM
Lazy Singleton : Double locking Singleton & : Initialization-on-demand_holder_idiom singleton
Have a look at below code:
public final class Singleton{
private static final Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public enum EnumSingleton {
INSTANCE;
}
public static void main(String args[]){
System.out.println("Singleton:"+Singleton.getInstance());
System.out.println("Enum.."+EnumSingleton.INSTANCE);
System.out.println("Lazy.."+LazySingleton.getInstance());
}
}
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
}
Related SE questions:
What is an efficient way to implement a singleton pattern in Java?
Query 2:
One Singleton instance is created per ClassLoader. If you want to avoid creation of Singleton object during Serializaiton, override below method and return same instance.
private Object readResolve() {
return instance;
}
Query 3:
To achieve a cluster level Singleton among multiple servers, store this Singleton object in a distributed caches like Terracotta, Coherence etc.
Singleton is a creational design pattern.
Intents of Singleton Design Pattern :
Ensure a class has only one instance, and provide a global point of
access to it.
Encapsulated "just-in-time initialization" or "initialization on
first use".
I'm showing three types of implementation here.
Just in time initialization (Allocates memory during the first run, even if you don't use it)
class Foo{
// Initialized in first run
private static Foo INSTANCE = new Foo();
/**
* Private constructor prevents instantiation from outside
*/
private Foo() {}
public static Foo getInstance(){
return INSTANCE;
}
}
Initialization on first use (or Lazy initialization)
class Bar{
private static Bar instance;
/**
* Private constructor prevents instantiation from outside
*/
private Bar() {}
public static Bar getInstance(){
if (instance == null){
// initialized in first call of getInstance()
instance = new Bar();
}
return instance;
}
}
This is another style of Lazy initialization but the advantage is, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). Read More at SourceMaking.com
class Blaa{
/**
* Private constructor prevents instantiation from outside
*/
private Blaa() {}
/**
* BlaaHolder is loaded on the first execution of Blaa.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class BlaaHolder{
public static Blaa INSTANCE = new Blaa();
}
public static Blaa getInstance(){
return BlaaHolder.INSTANCE;
}
}