I am implementing a singleton class in Java to make sure no more than one instance of the class is created.
Singletons are not threadsafe per default. The common way to create a singleton is to have a factory method that handles creation of the one instance. That way you can control instance creation.
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton() { ... }
}
Using a static instance variable is preferred to the internal "Holder" class. If you like, you can also make the static member private and provide a method for accessing it, but all that does is add another method call to the stack.
What about lazy instanciation: getInstance() returns the singleton or create it if it is the first call.
public class MySingleton
{
private static MySingleton instance;
private MySingleton()
{
// construct object . . .
}
// For lazy initialization
public static synchronized MySingleton getInstance()
{
if (instance==null)
{
instance = new MySingleton();
}
return instance;
}
// Remainder of class definition . . .
}
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.
If you care about concurrency, you won't be using shared global state.
Perhaps the best way is to use an enum with a single instance. This has the added benefit of being serializable and guaranteeing singleton-ness against serialization and reflection, which no "straightforward" Singleton implementation does (private? I have reflection, I scoff derisively at your access modifiers!). It's also very simple to implement:
public enum Singleton {
INSTANCE;
// fields and methods go here
}