What Is an Efficient Way to Implement a Singleton Pattern in Java

What is an efficient way to implement a singleton pattern in Java?

Use an enum:

public enum Foo {
INSTANCE;
}

Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):

The Right Way to Implement a Serializable Singleton

public enum Elvis {
INSTANCE;
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}

Edit: An online portion of "Effective Java" says:

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

Thread Safe Efficient way to implement singleton pattern in Java?

The most efficient/simplest way to make a lazy loading Singleton is just

enum Singleton {
INSTANCE
}

Note: there is no need for locking as class loading is thread safe. The class is final by default and the constructor cannot be called via reflection. The INSTANCE will not be created until the INSTANCE, or the class is used. If you are worried the class might be accidentally used you can wrap the singleton in an inner class.

final class Singleton {
private Singleton() { }
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

IMHO, you have to be pretty paranoid to consider this a better solution.

Other Ways of Singleton in Java

No, it is not. You didn't declare myClass private static final, nor the getInstance() is static. The code also doesn't really compile.

Here's the Singleton idiom:

public class MyClass {
private static final MyClass myClass = new MyClass();

private MyClass() {}

public static MyClass getInstance() {
return myClass;
}
}

It should be private, so that nobody else can access it directly. It should be static so that there's only one of it. It should be final so that it cannot be reassigned. You also need to instantiate it directly during declaration so that you don't need to worry (that much) about threading.

If the loading is expensive and you thus rather prefer lazy loading of the Singleton, then consider the Singleton holder idiom which does initialization on demand instead of during classloading:

public class MyClass {
private MyClass() {}

private static class LazyHolder {
private static final MyClass myClass = new MyClass();
}

public static MyClass getInstance() {
return LazyHolder.myClass;
}
}

You should however put big question marks whether you need a Singleton or not. Often it's not needed. Just a static variable, an enum, a factory class and/or dependency injection is often the better choice.

advantage of enum over class in singleton pattern

As explained by Joshua Bloch, the two approaches are functionally identical if your singleton is not serializable. Although you may wish to add code to your private Singleton constructor to prevent reflection being used to create a second instance.

If your singleton is serializable, then the enum approach will provide all the necessary plumbing for free, whereas with the static field approach, you have to add that yourself.

In my view, there is no downside to adopting the enum approach.

Creating singleton object, best way

You can try to use an enum like this:-

public enum Foo
{
INSTANCE;
}

Also check out the related answer:- What is an efficient way to implement a singleton pattern in Java?

Quoting few lines from the Enforce the Singleton Property with a Private Constructor or an enum Type which Stephen Denne has used in the above answer:-

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.

Singleton Pattern Recommended Method

Without going into all the stuff about singletons being an antipattern (but you should read up on it!), the currently best way to make a singleton in Java is to use an enum.

public enum Singleton {
INSTANCE;
}

The reason this is better is because the JVM guarantees that only one instance of the enum (per classloader) will exist at any time. It is thread safe, and you cannot use reflection to create another instance of the singleton.

Enum-values are also lazily instantiated, so you won't create the singleton before you access Singleton.INSTANCE the first time.



Related Topics



Leave a reply



Submit