Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Singleton

DZone's Guide to

Singleton

·
Free Resource
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;
	}
}
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}