Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton vs public static final variable

Tags:

java

singleton

So I know that the singleton pattern is implemented like this:

public class ClassName {
    private static ClassName instance;

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

    private ClassName() {}
}

What I want to ask is why you couldn't just do it like this:

public class ClassName {
    public static final ClassName instance = new ClassName();
    private ClassName() {}
}

Way fewer lines of code and seems to do exactly the same thing. Minus the lazy initialization of course, but I don't see why lazy initialization would be a significant benefit anyway. I'm not very experienced and would appreciate if you would enlighten me with your knowledge, thanks.

like image 957
Just some guy Avatar asked Feb 09 '23 01:02

Just some guy


2 Answers

Initializing the singleton instance inline and letting the classloader worry about synchronization may not be an extremely common practice, but it's definitely not unheard of.

The common idiom, however, is to have the instance variable private and return it through a getter so that no other code depends on it directly. That way, if in the future you decide you want something fancier (like, e.g., lazy initialization you mentioned), you can easily refactor your code without breaking the API:

public class ClassName {
    private static final ClassName instance = new ClassName();

    public static ClassName getInstance() {
        return instance;
    }

    private ClassName() {}
}
like image 64
Mureinik Avatar answered Feb 11 '23 15:02

Mureinik


Your first code use lazy creation with the synchronized keyword. instance = new ClassName() the problem with these kind of code is that the instance var could became non-null before the construction of the singleton and can be interpret in pseudo-code, that the JRE do for create the instance :

mem = allocate() ;
instance = mem ;
ctorSingleton(instance)

So if multiple threads access the method getInstance in same time, is it possible you get a new instance, because in java you have 2 instructions and the pseudo-code that the JRE interpret do it in 3.

I consider your second implement is the good one, because you are the sure it will work fine, and Thread or synchronisation problem are hard to fix.

This come from french article : http://christophej.developpez.com/tutoriel/java/singleton/multithread/

like image 29
fabien t Avatar answered Feb 11 '23 16:02

fabien t