Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the singleton pattern in Java

Tags:

java

singleton

Can anyone provide an example of a singleton pattern and explain why they are necessary?

like image 237
RKCY Avatar asked Jan 05 '10 20:01

RKCY


People also ask

How is singleton pattern implemented java?

To create the singleton class, we need to have static member of class, private constructor and static factory method. Static member: It gets memory only once because of static, itcontains the instance of the Singleton class. Private constructor: It will prevent to instantiate the Singleton class from outside the class.

What is the best way to implement Singleton in java?

1. Eager initialization: In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a Singleton class. By making the constructor as private you are not allowing other class to create a new instance of the class you want to create the Singleton.


3 Answers

Before going the singleton route, reconsider. Do you really need a singleton? If you're asking for scenarios when you need to implement singletons, it's because the need for them didn't really express. You're better off not introducing singletons in your code base just because it feels cool to follow design patterns.

Clean Code Talks - Global State and Singletons

Once Is Not Enough

Performant Singletons

However, what's really worth knowing is Dependency Injection.

Now if you really want to implement singletons in Java, I would recommend Joshua Bloch's "Effective Java" way of implementing them:

public class Singleton
{
  public static Singleton getInstance() {
    return SingletonHolder.instance;
  }

  private Singleton() {}

  private static final class SingletonHolder {
    static final Singleton instance = new Singleton();    
  }
}

The JLS guarantees the JVM will not initialize instance until someone calls getInstance();

Final note, the Double Checked Locking Pattern is broken in Java up to Java 5. The Java 5 memory model makes the DCL pattern thread safe but it makes it slower than the SingletonHolder class method while the original intent was performance optimization.

EDIT: As @Luno pointed out, since the second edition of the book, the preferred way is:

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.

like image 55
Gregory Pakosz Avatar answered Oct 05 '22 22:10

Gregory Pakosz


Basically, in Java you implement singleton by giving a class a private no-args constructor (private MyClass()), and statically (or lazily) initializing a single instance of the class which is returned by a static MyClass getInstance() method.

You would use this when you want there to be no more than a single instance of your class throughout the entire application.

like image 36
danben Avatar answered Oct 05 '22 21:10

danben


danben has a pretty good summary of what a singleton is, so I won't rehash it.

As far as uses go, singletons are often thinly veiled implementations of global variables (which is a bad idea). They can be useful for things like message routers or manager classes (among other things).

like image 23
Seth Avatar answered Oct 05 '22 20:10

Seth