A singleton is a class that can be instantiated only one time in a JVM per class loader. Repeated calls always return the same instance. Ensures that a class has only one instance, and provide a global point of access. It can be an issue if singleton class gets loaded by multiple class loaders.
private static variable, private construtor, public static getInstance.
public class OnlyOne {
private static OnlyOne one = new OnlyOne();
private OnlyOne(){… } //private constructor. This class cannot be instantiated from outside.
public static OnlyOne getInstance() {
return one;
}
}
When to use: Use it when only a single instance of an object is required in memory for a single point of access.
- Accessing application specific properties through a singleton object, which reads them for the first time from a properties file and subsequent accesses are returned from in-memory objects. Also there could be another piece of code, which periodically synchronizes the in-memory properties when the values get modified in the underlying properties file. This piece of code accesses the in-memory objects through the singleton object (i.e. global point of access).
- Accessing in-memory object cache or object pool, or non-memory based resource pools like sockets, connections etc through a singleton object (i.e. global point of access).