Correct implementation of initialization-on-demand holder idiom - java

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).

Related

Implementing Singleton with an Enum (in Java)

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.

Can objects have access modifiers?

I was going through a piece of code when I came across this:
public class ClassicA {
private static ClassicA instance = null;
}
I have never used such a thing and wanted to know what it means and how it is used. Also, what is the purpose of the access modifier for the object? Any examples/links are welcome.
It probably means that ClassicA is a Singleton. It is usually involved with declaring a private constructor, and a single public static getInstance() method.
Singletons are used when you want to make sure there is only one global instance of ClassicA in your entire application. Instead of instantiating it, you call getInstance(), which will check if it was instantiated once or not. If it was, it will instantiate it, and store the the resulting object in the private instance field. If it was already constructed, just return the instance field without re-instantiating.
Note that this is considered bad practice. See: https://softwareengineering.stackexchange.com/questions/40373/so-singletons-are-bad-then-what
Well, the class ClassicA has a private and static field instance which is null.
If there are no getters/setters the only way to access that field would be using reflection.
Since this looks like a singleton, I guess there's a getter as well that returns instance and if it is null first creates an instance and assigns it to the field.
It's a (static) member of the class, and yes, these can have access modifiers. (And as others have noted, it indeed looks like a portion of a Singleton.)
its a singleton
basically the author intended there to be only 1 instance of this class alive (the instance field)
the constructor is probably private and used only within the class.
This is used typically for a class that exhibits the Singleton design pattern.
The point is that for these types of objects you only want a single instance at most. What you do is create a private constructor for the class and then usually a public static method called, getInstance in which you check if the private instance variable has been set yet or not. If it has not yet set, you create a new instance of the class and assign it to instance, then you return that instance. If the object was already created you simply return it. Like this:
public class MySingleton {
private static MySingleton instance=null;
private MySingleton() {
//do stuff
}
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
}
Then from throughout your program you can easily get the singleton object from anywhere.
Thus, a singleton is effectively just a glorified global variable in languages such as PHP. I would argue though that it is a lot cleaner as you can prevent others from reassigning the reference to the instance and other trickery that may be very bad from a design standpoint.
Typically people use it for classes that manage some type of data access, such as a DB object, for Factory classes and builder classes, see this for more info
This is used for singleton pattern. See here
private static means that the instance is available to all the instances and static methods of the class, but only to them. It's actually like having static private method.
Such tricks can be used for example for implementing a singleton: you keep internally a single instance of a class, and you can give it to the class's clients on demand. Or for any other case when you need something shared just between the static methods and instances of some class.

Initialize-On-Demand idiom vs simple static initializer in Singleton implementation

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

Difference between singleton class and static class? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Difference between static class and singleton pattern?
What is the difference between a Singleton pattern and a static class in Java?
HI
I am not clearly getting What’s the difference between a singleton class and a static class?
Can anybody elaborate this with example?
Singleton Class: Singleton Class is class of which only single instance can exists per classloader.
Static/Helper Class (Class with only static fields/methods): No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.
Following is referenced from this blog "Static classes in Java" describes it nicely. The blog also has examples for explaining same:
Singleton example:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if (instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Static Class example:
/**
* A helper class with useful static utility functions.
*/
public final class ActionHelper {
/**
* private constructor to stop people instantiating it.
*/
private ActionHelper() {
// this is never run
}
/**
* prints hello world and then the users name
*
* #param users
* name
*/
public static void printHelloWorld(final String name) {
System.out.println("Hello World its " + name);
}
}
So what's the difference between the two examples and why do I think the second solution is better for a class you don't want or need to instantiate. Firstly the Singleton pattern is very useful if you want to create one instance of a class. For my helper class we don't really want to instantiate any copy's of the class. The reason why you shouldn't use a Singleton class is because for this helper class we don't use any variables. The singleton class would be useful if it contained a set of variables that we wanted only one set of and the methods used those variables but in our helper class we don't use any variables apart from the ones passed in (which we make final). For this reason I don't believe we want a singleton Instance because we do not want any variables and we don't want anyone instantianting this class. So if you don't want anyone instantiating the class, which is normally if you have some kind of helper/utils class then I use the what I call the static class, a class with a private constructor and only consists of Static methods without any any variables.
Same answer is also referenced from my answer here
Old que/ans on SO : Difference between static class and singleton pattern?
A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.
Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.
The difference is not the correct way to ask.because singleton is not a keyword compared to static. you should be asking like "When to choose which one?". what are the advantages of singleton class over static class, these questions comes at the design stages.
Singleton:
Usage:
classes that serve as global configuration , ex: Trial version of software with one database connection, JDK Runtime classes instances per jvm.
When to go:
1.While developing your code,you think of forward compatibilty, like tomorrow when you need to convert this singleton class to normal class or allow subclassing.
2. You can provide lazy loading feature , when this singleton class is heavy.
static:
Usage:
classes that basically does conversions,utility functions. please check Math class.
When to go:
1. helper classes, used by all the classes in your api development.
disadvantage:
1. classes are eagerly loaded .
expecting points from other people.
It's the difference between a pattern and how the pattern is implemented.
The Singleton pattern is not tied specifically to the Java language. There may be different ways of making a class into a singleton, depending on the language you use. Many OO languages use the equivalent of static variables to make a singleton, but others might use different techniques.
Also, some ways of implementing a singleton are better than others. One good way of implementing a Singleton is to properly encapsulate access to that Singleton through a factory method:
public class Example {
private static final Example SINGLETON = new Example();
public static Example getInstance() { return SINGLETON; }
private Example() { /* Constructor */ }
}
Using this technique, you can do all sorts of sophisticated things: lazy-load the singleton, replace it with some subclass, manage the singletons initialation via configuration, and so forth.
A Singleton is not a type of a class but a design pattern. With Singleton you (try to) guarantee, that only one instance of a certain class is ever constructed inside a single Java Virtual Machine. Modern implementations of the singleton pattern use enums, by the way. Older implementations use a private constructor and store the reference to the single instance in a static field.
A static class is always a member class which, in contrast to an inner class, has no access to instance variables of the surrounding class.
Static class example
public class A {
public static class B {
}
public int notAccessibleForB;
public static int accessibleForB;
}
Singleton pattern (simple old style)
public final class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton(){}
}
Singleton pattern (simple modern style)
public enum Singleton {
INSTANCE;
}

How do I make other classes derive from a singleton class?

I am sorry if this is a duplicate or too elementary, but how do I make a singleton class that can be subclassed?
Steve Yegge has an amusing article about singletons that mentions subclassing in this quote:
Then there's the subclassing thing.
It's almost impossible to subclass a
Singleton, and if you manage it, then
you shouldn't have been using a
Singleton in the first place. You
don't even want to go there. I've
walked roads that I dare not recount.
Just pretend you can't do it, and
you'll save yourself amazing amounts
of pain.
You generally can't, in any useful sense. This would be yet another reason to not use Singleton classes.
Actually, I don't think it is possible.
You make a class singleton by declaring its constructor(s) to be private. But if you then try to declare a subclass of your singleton class, the subclasses constructor wont be able to see the constructors of the superclass ... so they won't compile; e.g.
public class A () {
private A() { }
}
public class B () {
private B() { }
}
Both the Sun JDK 1.6 and Eclipse Ganymede compiler give a compilation error in the constructor B, to the effect that the no-args constructor for A is not visible.
You could increase the visibility of the private constructors, but then there is nothing (apart from good sense) stopping someone from creating multiple instances of it. In other words it is not really a singleton class anymore.
EDIT: I guess a kosher alternative would be to define a tree of one or more abstract (non-singleton) classes with the methods / members that you want to be common, and then define multiple singleton classes as a leaf classes as appropriate. But that is NOT one singleton class subclassing another one.
If you have defined your singleton as:
public class Singleton {
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
private Singleton() {
}
}
Then you can just do:
public class NewSingleton extends Singleton {
}
But, you won't be able to use the private methods so if you want to use the singleton you will still need to call Singleton.getInstance(); so you gain nothing by extending it.
But, there is no reason why you can't do it.
Now, if you want to add more functions to the Singleton class then you can use inter-type aspects from AspectJ and just inject new methods/properties into the Singleton which could then be used by the Singleton.
Singleton limits instances not the inheritance. Well - as already been pointed out it limits usefulness of inheritance and then you can relax private constructor to packaged or protected (which you may argue diminishes singletoness of the singleton) But what is the purpose?
As others have replied already, the uses of singleton subclassing are small. If you need a strategy pattern in the context of a singleton, you could define an interface and delegate to an implementation of that interface in the singleton instance. This moves the problem one layer down and makes it more clear why you would want to do it.
To answer your question; assuming the choice for the particular subclass your application uses is defined in for instance the system properties, you can do something like:
public static synchronised Singleton getInstance() {
if (instance == null) {
String clsName = System.getProperties().getProperty("singleton.class");
if (className == null || 0 == clasName.length()) {
instance = new Singleton();
} else {
Class cls = Class.forName(clsName);
instance = (Singleton) cls.newInstance();
}
}
return instance;
}
Disclaimer: untested code, add exception handling, etc :-)
Btw, make sure your getInstance() method is synchronised.

Categories