DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Weei has posted 5 posts at DZone. View Full User Profile

Singleton

02.13.2007
| 4633 views |
  • submit to reddit
        The proper way of implementing a Singleton.

public class MySingleton {
    private static final MySingleton INSTANCE = new MySingleton();

    private MySingleton() {}

    public static final MySingleton getInstance() {
      return INSTANCE;
    }
	 
	/**
	* Normal deserialization returns a new instance of an object. This ensures that only one instance is in existence. 
         * Deserialization can either create a new instance and leave the deserialized object to be garbage collected or
         * reuse the deserialized instance.
	*/
	private Object readResolve() throws ObjectStreamException {
	  return INSTANCE;
	}
}
    

Comments

Snippets Manager replied on Tue, 2007/12/11 - 9:17pm

You forgot the 'implements Serializable' in the class definition.

Weei Jye Chay replied on Tue, 2007/02/13 - 10:39pm

thanks, but lets stick to 'singleton'.

Snippets Manager replied on Thu, 2007/02/15 - 5:01pm

For this to be the "proper" way of implementing a Singleton, there are two things missing IMHO: - lazy initialization - exception/error handling (or logging, at least) for the constructor call