Anton Samokat
Anton Samokat

Reputation: 1136

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;

    private Singleton() {
    }

    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?

Upvotes: 0

Views: 256

Answers (2)

Phil Anderson
Phil Anderson

Reputation: 3146

To answer your question... No, it's not correct.

You say it's OK for it to be loaded several times, but in that case then it's not a singleton. The defining characteristic of a singleton is that there can only ever be one instance.

If it's OK for there to be several, then why make it a singleton at all?

If it's just stateless util methods then why not just make the static?

Upvotes: 2

Alexander Torstling
Alexander Torstling

Reputation: 18898

If your class is entirely stateless - make it a util class with only static functions.

If you have state and want a semi-singleton I would say that what you have done is misleading since there is no way for the reader to know if you were aware of the fact that you can get multiple instances or not. If you decide to stick with your posted code - rename it multiton or document the behaviour carefully. But don't do it just to reduce boilerplate though - you are in fact creating more problems for the reader than you are removing.

In my opinion the "Initialization on Demand Holder" idiom is the nicest singleton pattern. But I would recommend against Singletons in general. You would be better off passing a reference to a shared instance to your thread when you start it.

Upvotes: 3

Related Questions