The simplest way to create a Singleton in a thread safe manner in Java is to:
public class A {
private static A instance = new A();
private A() {}
public static A getInstance()
{
return instance;
}
}
To briefly describe that: The constructor is private to avoid instantiations. The public getInstance() method is used to get an instance of the class. getInstance() simply returns the private static instance variable. The JVM guarantees there will only ever be one private static instance variable.
I would always use the above but there is another alternative that works:
class Foo {
private static class BarHolder
{
public static Bar bar = new Bar();
}
public static Bar getInstance()
{
return BarHolder.bar;
}
}
This is different in that the singleton class Foo does not itself hold a private static variable, it delgates that to the private static BarHolder class. BarHolder has a public static Bar variable and that is accessed via the getInstance() method of the singleton. This pattern can be used when you don’t necessarily want the singleton instance to be created when the JVM loads the class.
Sign up for our daily email newsletter:
You must log in to post a comment.