The Perfect Singleton

From time to time I met Java programmers that are not really sure how they should implement Singleton pattern properly. (if you don’t have an idea what Singleton is just try Wikipedia: Singleton pattern).

And I’m not talking about proper implementation in threaded environment. But using the most common implementation you can find over internet you can easily create as many singletons as you like.

Just imagine you have the following common singleton implementation:

public final class NonSafeSingleton implements Serializable {

    private static final NonSafeSingleton INSTANCE = new NonSafeSingleton();

    private NonSafeSingleton() {}

    public static NonSafeSingleton getInstance() {
        return INSTANCE;
    }
}

Now concentrate on Serializable word. Think for one more second… Yes you’re right. If you send this stuff over RMI you’ll get second instance. It should even be enough to do some in memory serialization and de-serialization and kaboom! You’ve just blown away general Singleton contract. That’s not very nice. But how to fix that? Generally there are two ways I use:

  1. The hard way (or you use 1.4 or older Java)
    You need to implement readResolve method in your Singleton class. This small thing is used to override what serialization mechanism has created. What you return there will be used instead of data that came from serialization (for details check: Serializable Javadoc). Just return your instance here:

    ...
        protected Object readResolve() throws ObjectStreamException {
            return INSTANCE;
        }
    ...
  2. The easy way (Yes, I’m using 1.5 or newer)
    Change your singleton class to enum and remove private constructor and getInstance method. Yes it’s really that simple. You get this for free then.

    public enum SafeSingleton implements Serializable {
    
        INSTANCE;
    }

Just keep this in mind when implementing next Singleton. It can make your life easier if you use RMI heavily.

Reference: The Perfect Singleton from our JCG partner Marek Piechut at the Development world stories.

Related Articles :
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

One Response to "The Perfect Singleton"

  1. manoj says:

    What is instance control?

    Instance control basically refers to single instance of the class OR singleton design pattern .

    Java 1.5 onwards we should always prefer ENUM to create singleton instance. It is absolutely safe . JVM guarantees that. All earlier mechanical of controlling instance to single are already broken.

    So in any interview you can confidently say ENUM= provides perfect singleton implementation .

    Now what is readResolve?

    readResolve is nothing but a method provided in serializable class . This method is invoked when serialized object is deserialized. Through readResolve method you can control how instance will be created at the time of deserialization.Lets try to understand some code

    public class President {

    private static final President singlePresident = new President();

    private President(){

    }

    }

    This class generates single instance of President class. singlePresident is static instance and same will be used across.

    But do you see it breaks anywhere?

    Please visit http://efectivejava.blogspot.in/ for more details on this

Leave a Reply


two + = 3



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books