Saturday, July 01, 2006

what is singleton?

A singleton class is one in which instantiation is restricted to ensure that only one instance is created for the current Java Virtual Machine. Singletons usually have a private default constructor, to prevent direct instantiation, and a static method to obtain a "new" reference to the single instance. On its first call, the static instance method creates the object using a private constructor and stores a static reference to it for all subsequent calls.

This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist.

Singleton Example:
//For Single Thread safe
public class Singleton {
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}

// Correct multithreaded version for J2SE 1.4 and earlier
public class Singleton {
private Helper helper = null;
public synchronized Helper getHelper() {
if (helper == null)
helper = new Helper();
return helper;
}
// other functions and members...
}

What happens to singletons when two JVMs are running?

A: There is only one instance of a true singleton in a single virtual machine. If two virtual machines are running, two separate and independent instances of a singleton exist. If the singleton in question is governing access to the same system resource, there may be conflicts between the two systems, which is why the singleton design pattern is not ideal in this scenario.

For more details on J2EE Patterns by Sun

No comments: