Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a singleton class threadsafe?

I am implementing a singleton class in Java to make sure no more than one instance of the class is created.

like image 623
AJ. Avatar asked Sep 30 '09 07:09

AJ.


1 Answers

The best way to make a singleton? Use an enum.

public enum Singleton {
    INSTANCE;
    public void foo(){ ... }
}

// Usage:
Singleton.INSTANCE.foo();

You get lots of help from the VM not only to avoid double instantiation, but it also helps you avoid deserialization corruption.

like image 77
gustafc Avatar answered Nov 14 '22 23:11

gustafc