Never been to DZone Snippets before?

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

Singleton (See related posts)

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 on this post

handtwerk posts on Feb 15, 2007 at 16:06
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
wjchay posts on Mar 22, 2007 at 07:39
thanks, but lets stick to 'singleton'.
ITVGuy2000 posts on Dec 11, 2007 at 20:19
You forgot the 'implements Serializable' in the class definition.

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts