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.
Related
I'm dealing with a contractor's code. For whatever reason he has made a series of "constants" files that are all interfaces. They look like this:
interface SomeTypeConsts {
public static class SomeSubTypeA {
public static final String CONSTANT_A = "foo";
public static final String CONSTANT_B = "bar";
}
public static class SomeSubTypeB {
public static final String CONSTANT_A = "baz";
}
}
and so forth. There are no unimplemented/abstract methods, the files just contain nested classes some arbitrary level deep, and static final Strings for the constants. I cannot modify the contractor's code at this time.
I'm writing a test framework and I need an instance of one of these constants interfaces. All of them follow the above pattern, but my method needs to support all of them and not just one in specific.
I tried instantiating the interface using Reflection like this:
clazz.newInstance() // where clazz is Class<SomeTypeConsts>
But it threw a java.lang.InstantiationException.
All of the questions here on SO say that you need to implement the interface first, then use that instance. And if I knew ahead of time which const interface it was, I could easily do SomeTypeConsts consts = new SomeTypeConsts(){};. But I haven't been able to figure out how to do this with reflection, when all I have to work with is the Class<SomeTypeConst>.
Given an interface Class reference, with no abstract methods to be overwritten/implemented, how can I instantiate an instance of it using reflection?
You could do this using a JDK proxy for the interface, but it would be entirely pointless: If all you're doing is accessing static members, all of that is resolved without reference to any actual instance of the type in question, either at compile-time (far preferable) or at runtime with some approach like enumerating the fields and filtering on the static ones.
From the language spec (emphasis mine):
This type has no instance variables, and typically declares one or more abstract methods; otherwise unrelated classes can implement the interface by providing implementations for its abstract methods. Interfaces may not be directly instantiated.
And, from the Javadoc of Class.newInstance():
[throws] InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.
You can't instantiate an interface. You can only instantiate (non-abstract) classes which implement it.
No. You cannot do that. Interfaces by definition are not instantiable.
What you need is a mock object. Not reflection
When the Gang of four introduced the singleton pattern, they also had to explain, why not to use static class fields and method instead. The reason was: the possibility to inherit. For Java it had sense - we cannot normally inherit the class fields and methods.
Later the "Effective Java" book appeared. And we know now that the existence of reflection destroys the singularity of the singleton class with private constructor. And the only way to make a real SINGLEton is to make it as a single item of an enumeration. Nice. I had done some myself this way.
But a question remains: While we cannot inherit from enumeration, what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Edit. Thanks to the #bayou.io I see that in https://softwareengineering.stackexchange.com/a/204181/44104 there is a code that can trick the enum, too, and create again two exemplars of the enum singleton. The other problems are mentioned there, too. So, there is no need to use enum instead of the usual singleton class pattern, too? BTW, all enum pluses that are mentioned here till now, work for singleton classes, too.
what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Because enum is an object so it can not only be passed around but also implement interfaces.
Also since we are making a class, we can use the different public/private options available to all kinds of classes.
So in practice, we can make a singleton that implements an interface and then pass it around in our code and the calling code is non the wiser. We can also make the enum class package private but still pass it around to other classes in other packages that expect the interface.
If we used the static methods version, then the calling class would have to know that this object is a singleton, and our singleton class would have to be public so the other classes can see it and use it's methods.
There's nothing particularly wrong with the "good old fashioned singleton", enum "singletons" are just convenient - it saves you the need to muck around with boiler-plated code that looks the same in every singelton.
To me, a singleton makes sense wherever you want to represent something which is unique in its kind.
As an example, if we wanted to model the Sun, it could not be a normal class, because there is only one Sun. However it makes sense to make it inherit from a Star class. In this case I would opt for a static instance, with a static getter.
To clarify, here is what I'm talking about :
public class Star {
private final String name;
private final double density, massInKg;
public Star(String name, double density, double massInKg) {
// ...
}
public void explode() {
// ...
}
}
public final class Sun extends Star {
public static final Sun INSTANCE = new Sun();
private Sun() { super("The shiniest of all", /**...**/, /**...**/); }
}
Sun can use all the methods of Star and define new ones. This would not be possible with an enum (extending a class, I mean).
If there is no need to model this kind of inheritance relationships, as you said, the enum becomes better suited, or at least easier and clearer. For example, if an application has a single ApplicationContext per JVM, it makes sense to have it as a singleton and it usually doesn't require to inherit from anything or to be extendable. I would then use an enum.
Note that in some languages such as Scala, there is a special keyword for singletons (object) which not only enables to easily define singletons but also completely replaces the notion of static method or field.
ENUM singletons are easy to write. It will occupy very less code, which is clean & elegant if you compare with implementation of lazy singleton with double synchronized blocks
public enum EasySingleton{
INSTANCE;
}
Creation of ENUM instance is thread safe.
ENUM singletons handled serialization by themselves.
conventional Singletons implementing Serializable interface are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton
private Object readResolve(){
return INSTANCE;
}
Have a look at this article on singleton
I have got two versions of "Initialization-on-demand holder idiom":
http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh
The major difference between above is that the first one declared INSTANCE as private, but the second one declared INSTANCE as public.
Please tell me which one should I use.
Sorry, I have not found the difference between using private and public in my application:
public class Singleton {
private int x;
public int getX() {
return x;
}
private Singleton () {}
private static class LazyHolder {
//both private and public works
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
The only thing I do is to call something like Singleton.getInsance().getX(), so both versions works.
Thus I want to know the situations for using them.
There are several things to explain about singletons and the initialization-on-demand holder idiom. Here we go:
1) The access modifier:
Normally you can't access fields and methods in another class if they are private. They must at least be package private (having no modifier, it is) if the accessing class is in the same package. So the correct way to implement it, would be:
public class Singleton {
...
private static class LazyHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
However, JLS 6.6.1 explains:
Otherwise, if the member or constructor is declared private, then access is
permitted if and only if it occurs within the body of the top level class (§7.6)
that encloses the declaration of the member or constructor.
That means, declaring the field INSTANCE as private still allows the access from inside the top level class Singleton. But the compiler must do some tricks to get around the private modifier: It inserts package private methods for getting and setting such a field.
In fact, it does not matter, which modifier you place on it. If it is public, it still cannot be accessed from other classes than Singleton. However ... I think the package private access is the best. Making it public does not makes sense. Making it private forces the compiler to do some tricks. Making it package private reflects what you have: Access to a class member from another class.
2) How to implement a singleton:
If you ever want to consider serialization, the singleton implementation will get a bit difficult. Joshu Bloch wrote a great section in his book "Effective Java" about implementing singletons. At the end, he concluded to simply use an enum for this, as the Java enum specification provides every charecteristic that is needed in regards to singletons. Of course, that does not use the idiom anymore.
3) Considering design:
In most design decisions, singletons do not have their places anymore. In fact, it could indicate a design issue, if you must place a singleton into your program. Keep in mind: Singletons provide a global acess mechanism to some data or services. And this is not OOP.
private static class LazyHolder {
$VISIBILITY static final Singleton INSTANCE = new Singleton();
From a consumer's point of view it does not really matter if $VISIBILITY is public or private because the LazyHolder type is private. The variable is only accessible via the static method in both cases.
I use number 1 (private INSTANCE) because you generally try to use the narrowest scope as possible. But in this case since the Holder class is private it doesn't really matter. However, suppose someone later decided to make the Holder class public then number 2 could be problematic from an encapsulation perspective (callers could bypass the getInstance() method and access the static field directly).
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.
I am just trying to understand why all fields defined in an Interface are implicitly static and final. The idea of keeping fields static makes sense to me as you can't have objects of an interface but why they are final (implicitly)?
Any one knows why Java designers went with making the fields in an interface static and final?
An interface is intended to specify an interaction contract, not implementation details. A developer should be able to use an implementation just by looking at the interface, and not have to look inside the class which implements it.
An interface does not allow you to create an instance of it, because you cannot specify constructors. So it cannot have instance state, although interface fields can define constants, which are implicitly static and final.
You cannot specify method bodies or initializer blocks in an interface, although since Java 8 you can specify default methods with bodies. This feature is intended to allow new methods to be added to existing interfaces without having to update all the implementations. But you still cannot execute such a method, without first creating an instance implementing the interface.
Aside: Note that you can implement an interface with an anonymous inner class:
interface Foo {
String bar();
}
class FooBar {
Foo anonymous = new Foo() {
public String bar() {
return "The Laundromat Café";
};
}
You have to provide the full implementation of the interface for the anonymous inner class to compile.
new Foo() is initializing the anonymous inner class with its default constructor.
Reason for being final
Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation. An interface is a pure specification without any implementation.
Reason for being static
If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.
There are a couple of points glossed over here:
Just because fields in an interface are implicitly static final does not mean they must be compile-time constants, or even immutable. You can define e.g.
interface I {
String TOKEN = SomeOtherClass.heavyComputation();
JButton BAD_IDEA = new JButton("hello");
}
(Beware that doing this inside an annotation definition can confuse javac, relating to the fact that the above actually compiles to a static initializer.)
Also, the reason for this restriction is more stylistic than technical, and a lot of people would like to see it be relaxed.
The fields must be static because they can't be abstract (like methods can). Because they can't be abstract, the implementers will not be able to logically provide the different implementation of the fields.
The fields must be final, I think, because the fields may be accessed by many different implementers allows they to be changeable might be problematic (as synchronization). Also to avoid it to be re-implemented (hidden).
Just my thought.
I consider the requirement that the fields be final as unduly restrictive and a mistake by the Java language designers. There are times, e.g. tree handling, when you need to set constants in the implementation which are required to perform operations on an object of the interface type. Selecting a code path on the implementing class is a kludge. The workaround which I use is to define an interface function and implement it by returning a literal:
public interface iMine {
String __ImplementationConstant();
...
}
public class AClass implements iMine {
public String __ImplementationConstant(){
return "AClass value for the Implementation Constant";
}
...
}
public class BClass implements iMine {
public String __ImplementationConstant(){
return "BClass value for the Implementation Constant";
}
...
}
However, it would be simpler, clearer and less prone to aberrant implementation to use this syntax:
public interface iMine {
String __ImplementationConstant;
...
}
public class AClass implements iMine {
public static String __ImplementationConstant =
"AClass value for the Implementation Constant";
...
}
public class BClass implements iMine {
public static String __ImplementationConstant =
"BClass value for the Implementation Constant";
...
}
Specification, contracts... The machine instruction for field access uses object address plus field offset. Since classes can implement many interfaces, there is no way to make non-final interface field to have the same offset in all classes that extend this interface. Therefore different mechanism for field access must be implemented: two memory accesses (get field offset, get field value) instead of one plus maintaining kind of virtual field table (analog of virtual method table). Guess they just didn't want to complicate jvm for functionality that can be easily simulated via existing stuff (methods).
In scala we can have fields in interfaces, though internally they are implemented as I explained above (as methods).
static:
Anything (variable or method) that is static in Java can be invoked as Classname.variablename or Classname.methodname or directly. It is not compulsory to invoke it only by using object name.
In interface, objects cannot be declared and static makes it possible to invoke variables just through class name without the need of object name.
final:
It helps to maintain a constant value for a variable as it can't be overridden in its subclasses.