jeudi 28 mai 2015

When to use proper version of singleton thread-safe implementation?

I have a stateless helper-like class which I want to make as a singleton. This class will be shared across different threads.

Am I correct that in this case (instance does not require huge memory allocation size and thus can be loaded several times without resources and performance impact) there is no need in implementing such a singleton with proper multi-threading lazy initialization strategy (Double Checked Locking & volatile, On Demand Holder idiom, Enum Singleton, Synchronized Accessor)?

Is it right to implement such a singleton with a simple non-multi-threading lazy initialization version strategy (like in the code below) in order to have less amount of boilerplate code?

public class Singleton {
    private static Singleton INSTANCE;

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

And only in case when state of the singleton class shared across different threads it is required to add proper multi-threading version of a singleton initialization?

Aucun commentaire:

Enregistrer un commentaire