Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety in Singleton

I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:

class Singleton{
    private static Singleton instance;

    private Singleton(){}

    public static synchronized Singleton getInstance(){
        if(instance == null) instance = new Singleton();
        return instance;
    }
}

Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)

like image 653
Robert Avatar asked May 26 '10 11:05

Robert


People also ask

How do you ensure thread safety in singleton?

Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.

What is thread safe singleton C#?

Thread Safety Singleton In the code, the thread is locked on a shared object and checks whether an instance has been created or not. It takes care of the memory barrier issue and ensures that only one thread will create an instance.

Is singleton thread safe Swift?

In Swift, any variable declared with the let keyword is a constant and, therefore, read-only and thread-safe. When a variable is declared as var it becomes mutable and not thread-safe unless the data type is specifically designed to be thread-safe when mutable.

Is double locking must to create thread safe singleton class?

In double-checked locking, code checks for an existing instance of Singleton class twice with and without locking to make sure that only one instance of singleton gets created. Need of Double-checked Locking of Singleton Class: Java.


1 Answers

Josh Bloch recommends using a single-element enum type to implement singletons (see Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type).

Some people think this is a hack, since it doesn't clearly convey intent, but it does work.

The following example is taken straight from the book.

public enum Elvis {
   INSTANCE;

   public void leaveTheBuilding() { ... }
}

Here is his closing arguments:

This approach [...] is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiations, 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.


On enum constant singleton guarantee

JLS 8.9. Enums

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 (§15.9.1).

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.


On lazy initialization

The following snippet:

public class LazyElvis {
    enum Elvis {
        THE_ONE;
        Elvis() {
            System.out.println("I'M STILL ALIVE!!!");
        }       
    }
    public static void main(String[] args) {
        System.out.println("La-dee-daaa...");
        System.out.println(Elvis.THE_ONE);
    }
}

Produces the following output:

La-dee-daaa...
I'M STILL ALIVE!!!
THE_ONE

As you can see, THE_ONE constant is not instantiated through the constructor until the first time it's accessed.

like image 101
polygenelubricants Avatar answered Sep 18 '22 12:09

polygenelubricants