Breaking the Singleton

One of my colleagues at work raised a question regarding ‘breaking the singleton’ using Java Reflection, and asked of a way to avoid such actions. It inspired me, and started to think about a way to avoid it, and following is the outcome of it.

A word of caution before continuing any further. I do not recommend at all that any of the following methods (except for SecurityManagers) shall be used in your code to restrict reflective access to your singletons. Such access is possible in Java because there is a good reason. Sometimes, when you are working with old code (may be even not so old code), you might need to be able to reflectively access the singleton, and you might not be able to predict that at the time of writing your code.

Singleton pattern can be broken using reflection, as shown below.

Singleton class:

package com.test.singleton.securitymgr;

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
        System.out.println("Singleton Constructor Running...");
    }

    public static final Singleton getInstance() {
        return INSTANCE;
    }
}

Test class:

package com.test.singleton.securitymgr;

import java.lang.reflect.Constructor;

public class Test {

    public static void main(String[] args) throws Exception {

        Singleton s = Singleton.getInstance();

        Class clazz = Singleton.class;

        Constructor cons = clazz.getDeclaredConstructor();
        cons.setAccessible(true);

        Singleton s2 = (Singleton) cons.newInstance();
    }
}

Output:
Singleton Constructor Running...
Singleton Constructor Running...

Java’s own way of handling such mischievous behavior is to use a SecurityManager which restricts the ‘supressAccessChecks’permission of java.lang.reflect.ReflectPermission. The default security manager implementation does it. Following example shows this:

Test class:

package com.test.singleton.securitymgr;

import java.lang.reflect.Constructor;

public class Test {

    public static void main(String[] args) throws Exception {

        SecurityManager mgr = new SecurityManager();
        System.setSecurityManager(mgr);

        Singleton s = Singleton.getInstance();

        Class clazz = Singleton.class;

        Constructor cons = clazz.getDeclaredConstructor();
        cons.setAccessible(true);

        Singleton s2 = (Singleton) cons.newInstance();
    }
}

Output:
Singleton Constructor Running...
Exception in thread "main" java.security.AccessControlException: access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
at java.security.AccessController.checkPermission(AccessController.java:546)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:107)
at com.test.singleton.securitymgr.Test.main(Test.java:17)

But the downside of this is that some of the libraries that we use, for example ‘Hibernate’ relies on reflective access to object properties. When we mark a field (instead of public getter / setter) with @Id or @Column annotation, Hibernate uses reflection to access the particular field to obtain the meta-data. So if we put a security manager which restricts reflective access, theoretically Hibernate should fail (I haven’t tried this myself). There might be workarounds for this (may be annotating getters setters instead of field would fix this).
On the other hand, thinking about the problem, I thought of another solution, which seems to solve this. I didn’t put my mind into breaking this, so I’m not sure if this could be broken.
In this approach, the constructor checks to see if the instance variable is already set. If it is, then the constructor would throw an exception avoiding the instantiation.

Singleton class:

package com.test.singleton.custom;

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {

        // Check if we already have an instance
        if (INSTANCE != null) {
           throw new IllegalStateException("Singleton" +
             " instance already created.");
        }

        System.out.println("Singleton Constructor Running...");
    }

    public static final Singleton getInstance() {
        return INSTANCE;
    }
}

Test class:

package com.test.singleton.custom;

import java.lang.reflect.Constructor;

public class Test {
    public static void main(String[] args) throws Exception {

        Singleton s = Singleton.getInstance();

        Class clazz = Singleton.class;

        Constructor cons = clazz.getDeclaredConstructor();
        cons.setAccessible(true);

        Singleton s2 = (Singleton) cons.newInstance();        
    }
}

Output:
Singleton Constructor Running...
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.test.singleton.custom.Test.main(Test.java:15)
Caused by: java.lang.IllegalStateException: Singleton instance already created.
at com.test.singleton.custom.Singleton.(Singleton.java:12)
... 5 more

Apart from above, another case is when using lazily instantiated singletons as below, if the method which does the instantiation is not thread-safe, multiple instances could be created.

Singleton class:

package com.test.singleton.lazy;

public class LazySingleton {

    private static LazySingleton INSTANCE;

    private LazySingleton() {
    }

    // If this method is not synchronized, multiple instances
    // can be created
    public static synchronized LazySingleton getInstance() {

        if (INSTANCE == null) {
            // Lazily instatiate on-demand
            INSTANCE = new LazySingleton();
        }

        return INSTANCE;
    }
}

On the other hand, there’s another way to break the singleton pattern, which cannot be solved using either of above, and any way that I could think of. That is to use multiple class loaders. When the same class is loaded by two different class loaders, that same class is treated as if they are two different classes. That is because the Java identifies unique classes not only using it’s fully qualified name, but also with the class loader which loaded the class. If our singleton above is loaded by two class loaders, there will be two instances of it.

That being said, use of Singletons should be done with care, especially when the singleton maintains state. In distributed environments such as clusters (each VM will have its own singleton instance), relying on the “singleton-ness”of singletons could lead to hard to find bugs.


Update : Serializable Singletons (25-Sep-2009)

Another scenario where Singleton pattern could probably break is when using serialization. If the Singleton class is serializable, performing a deserialization could yield multiple instances. The solution provided above with a check in the constructor would not be able to resolve this, as constructors are not invoked at deserialization. However, it is possible to overcome this by implementing special methods provided by Java Serialization API such as writeReplace() / readResolve().

Following example demonstrates this. Thanks to Gireesh Kumar for bringing this up for discussion.

package com.test.singleton.serializable;

import java.io.Serializable;

public class Singleton implements Serializable {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {

        // Check if we already have an instance
        if (INSTANCE != null) {
           throw new IllegalStateException("Singleton" +
             " instance already created.");
        }

        System.out.println("Singleton Constructor Running...");
    }

    public static final Singleton getInstance() {
        return INSTANCE;
    }

    // This will fix the de-serialization issue
    private Object readResolve() {
         // Return the available instance instead.
         return INSTANCE;         
    }
}

Update : Improved Lazy Singleton (29-Sep-2009)

A reader (StarWars) has shown the lazy singleton implementation can be improved with the use of a static inner class for initializing the singleton. This would remove the necessity of synchronizing the getInstance() method, which would remove the synchronization overhead. Thanks to StarWars for suggesting this.

Additionally, this approach will also allow us to overcome the reflection vulnerability of Lazy Singleton.

The following code outlines the structure of the optimized version of Lazy Singleton.

package com.test.singleton.optimizedlazy;

public class OptimizedLazySingleton {

    /**
     * Singleton Instance Wrapper Class.
     * 
     * When this class is loaded, the singleton instance will be 
     * created. Since a class is loaded by a given class loader
     * only once, this will ensure that the Singleton-ness of the 
     * singleton will be preserved. 
     * 
     * Additionally, the class will be loaded on the first reference to it,
     * which will occur when the getInstance() method is executed for
     * the first time.
     */
    private static class SingletonInstanceWrapper {

        /**
         * Singleton Instance.
         */
        static final OptimizedLazySingleton INSTANCE = new OptimizedLazySingleton();

        static {
            System.out.println("Instance Wrapper Class Loaded");
        }
    }

    /**
     * Guarded Constructor.
     */
    private OptimizedLazySingleton() {

        // Check if we already have an instance
        if (SingletonInstanceWrapper.INSTANCE != null) {
            throw new IllegalStateException("Singleton" + " instance already created.");
        }

        System.out.println("Singleton Constructor Running...");
    }

    /**
     * Note that this method is no longer synchronized !
     */
    public static final OptimizedLazySingleton getInstance() {
        System.out.println("Returning Singleton...");
        return SingletonInstanceWrapper.INSTANCE;
    }
}

41 comments

  1. one could use objenesis (http://objenesis.org) to instantiate the singleton without calling the constructor. Also, I believe that you can ignore the security manager (at least on Sun's VM) using some internal classes that does not check for permissions (like some child of sun.reflect.ConstructorAccessor)

  2. Nice article but a little "dangerous" in my opinion.
    Given the fact that singletons are 95% of the time used in the wrong way (I think that usually it is much better to enforce singletonness externally by framework and not in the class itself) I wouldn't like to become mad to overcome the limits this article proposes only to mock some service!
    In other words I'm of the party "death to (wrong) singletons!" :-)

  3. There is Joshua Bloch's solution:

    public enum Singleton {
    INSTANCE;
    public int answer() {return 42;}
    }

    Heinz Kabutz recently wrote a column about hacking enums, but that isn't easy.

  4. @Riccardo

    Agreed with the point made :) . As you suggested, utilizing a framework (ex Spring) would be ideal, because then, even under distributed environments, we could take measures to ensure the singleton-ness of a singleton.

    Like I said in the beginning of the article, I don't recommend doing any of the stuff that I suggested ;) . It's just for the knowledge.

    @Eric

    Like you pointed out, using enum is a good choice. It could eliminate most of the hack-arounds that could be done using Reflection.

  5. The much bigger problem with raw Singleton (like in the example) is that it will result in untestable code. It is pretty hard to write JUnit test for classes that uses raw Singleton without any kind of abstraction like a DI framework.

    So you should avoid raw Singletons in the first place.

  6. Hi Gireesh,

    I missed the part about serialization / de-serialization in the article.

    You can control the behavior of serialization / de-serialization using methods such as writeReplace / readResolve.

    Regarding Singletons, you can avoid multiple instances by writing a readResolve() method in your Serializable singleton class, which would return the real Singleton instance.

    Ex.
    public class Singleton implements Serializable {
    private static final …. INSTANCE;

    // Rest of the code

    private Object readResolve() {
    return INSTANCE;
    }
    }

    I'll update the article with this information.

  7. I would much rather look at other tangible improvements instead of worrying about which developer would break my singleton using reflection!

  8. Seriously, why not just use a static class! I know people complain about how you can't extend a static class, but how many homemade singletons have you come across that are subclasses of singletons and accessed from a factory method? Uh… never seen anyone intentionally try to do that.

    Perhaps using static classes doesn't look as sexy, but at the end of the day it can really make things a lot less complicated.

  9. Like I've said in the article, I do not recommend doing these things in your day to day work. In most of the work we do, its not necessary to worry about somebody trying to break your singleton.

    But knowing that there are cases where your Singleton will not be a singleton might come handy in certain occasions. This may not apply to most of the general JEE / JSE development, but when developing API's, developer tools etc, these things do come handy.

  10. @Tim

    It is arguable about using Singletons vs Static Methods, but I think that depends on the situation. There are some situations where we could avoid singletons and rely on static methods, but there are some where singleton would rise and shine (ex. extend from another class, implement interfaces, lazy load).

    The following discussion at TSS seems to shed some light on this.

    http://www.theserverside.com/discussions/thread.tss?thread_id=25937

  11. Sometime ago, somewhere, I've seen a curious "pattern" called "Doubleton":

    public class MyDoubleton{
    private static MyDoubleton instance1 = new MyDoubleton();

    private static MyDoubleton instance2 = new MyDoubleton();

    private MyDoubleton (){
    // Nothing to do for awhile
    }

    public static MyDoubleton getInstance1(){
    return instance1;
    }

    public static MyDoubleton getInstance2(){
    return instance2;
    }
    }

  12. I sat down to come up with a good example of using a static class, but it turned out to be more of a factory method. Soo… yea. Maybe Singletons are THA BOMB! I just think Singletons are overused is all. But I digress…

    This blog post was very informative and I enjoyed the various scenarios posted. Nice work!

  13. @Tim

    "I sat down to come up with a good example of using a static class, but it turned out to be more of a factory method. Soo… yea. Maybe Singletons are THA BOMB!"

    I do not try to promote the use of Singletons :) . It's just that I wanted to pass the message that singletons may not be singletons at all in certain situations.

    Singletons should be avoided if possible, because Singletons impose restrictions on testability, distributed environments, etc, which was highlighted by several comments here as well.

    "I just think Singletons are overused is all. But I digress.."
    I agree with your point. Singletons are overused. I have seen (and also written myself) many instances where Singletons could have been avoided. In fact, in one of my projects (it was a Struts 2 Plugin), the product was not usable under clustered environments because of a Singleton, which I had to replace with a Spring based POJO in a later release.

    The bottom line is that Singletons should be avoided if possible. But Singletons are here to stay, and we all have to live with it.

  14. You'll never get your singleton safe from prying hands. Even with the check in the constructor you can just as easily use reflection to clear the field (Field.setValue() etc.) before calling the constructor. I agree singletons are evil and a class should only be managed as a singleton by it's surrounding, the class itself should be blissfully unaware that there is only a single instance created. This is the major problem I see with singletons.
    To put it into context, the composition of the application decides the singletonnes of a class, not the class itself.

  15. @marcel

    I dont think that you could use Field.set() to modify a static final field value (once its set). Of course, you can change the value of a final instance variable, but attempting to modify a static final will result in a java.lang.IllegalAccessException being thrown.

    But obvisouly, Lazy Singletons are exposed to attacks via reflection.

    I agree with you regarding Singleton-ness being determined by the users of the class. This is the case when general development is concerned. As long as we treat the singleton as a singleton, it will be a singleton :) .

    @Raees

    Thanks ! :)

  16. For lazy loaded singleton, you could use static inner class and define a static class final variable which has the reference to the instance. Since class initialization is serial its thread safe and you could avoid the overhead of synchronization.

  17. @Star wars

    Definitely. That would improve the performance of the getInstance() method, and also would fix the Refelction vulnerability as well.

    I'll update the article with your suggestion.

    Thanks a lot !

  18. Hi Santhosh,

    Yes, you are correct; of course with a little magic of AOP we can get that done, plus so much more.

    While there is no question about the power and capabilities of AOP, there are times in which we don't have the option of using anything other than the plain old core Java itself to deal with these type of intricacies.

  19. nice article: ) . did you already "effective java api 2"?
    This book give a prefect solution to impliment Singleton pattern :) : use simply enumeration

  20. Hi Kamel,

    Yes, I have read Effective Java 2nd Edition. Using enum's would remove most of the reflection based hacks. But it is a practice that is yet to be embraced by the developer community.

    So far, the common practice is to utilize Java classes for implementing Singletons.

    On the other hand, in a purist (which I am not) point of view, using enums as singletons would be using it for something other than the intended use of enums. Isn't it?

  21. Hi,

    If you are worried about someone would use reflection to create illegal instances of your singleton (non-enum) type, you could use information about the caller of the constructor inside the constructor. This actually also partly facilitates inheritance of singleton types!

    Information about the caller is easily obtained via a strack trace; the downside is that the JVM specs do not require (if I remember correctly) a stack trace to be available at all, and the code can quickly become cluttered!

    Anyways – consider the example below and assume CallerClass is a utility class using stack trace information. The example will disallow any caller that is not the class itself, hence preventing reflective invocation as well!


    // singleton type
    public final class Foo {
    __ private Foo() {
    ____ // Guard against reflection…
    ____ CallerClass caller = new CallerClass();
    ____ if (!caller.isThisClass()) {
    ______ throw new SingletonError(caller);
    ____ }
    __ }
    __ ..
    }

    For fully working examples, including complete source code and documentation, see http://www.rode.dk/thesis :)

    Regards / G.Rode

  22. Hi Rode,

    Your concept is interesting. I just skimmed through your thesis, and I have to say that it's a job well done. I hope to go through it thoroughly in my free time.

    Thanks a lot for sharing.

  23. Hi Yohan,

    You're welcome and thanks for the kind words! :)

    I you ever get around to skimming the thesis/website more thoroughly, feel free to use whatever you like from it on your blog…

    Regards / G.Rode

  24. Hi Mihir,

    It's a very good article, and explains most of the issues discussed here, much more in detail.

    Also it provides solutions to some of the problems that I did not had solutions for, such as Singletons with multiple class loaders.

    Thanks for sharing !

  25. Singleton is one of the most famous design patterns, that is being used quite a lot. However, some of the developers are unaware that the "singleton-ness" singleton pattern can be broken using different ways. This discussion is about breaking the Singleton pattern in Java using using different methods, and how to avoid some of those.

  26. Dear Yohan Liyanage,
    After reading hookup method by extending Thread class by a class to do some “tiny cleaning or logging operation” before the VM halts during some app error and not when terminated by os ( i hope i am saying what u really mean :D ) and after this singleton n caution explaination using reflection -i have come to an conclusion that
    i should request
    you to post an article as soon as possible about “Patterns + Example of Each , Easy Explanation about why and when it can be used and how it works “.
    When i read from different sources i get confused of what is really what and why and when since I’m beginner.
    With your explanation i surely believe i will become a expert for a good cause…
    Thank You

  27. Dear Yohan Liyanage,
    After reading hookup method by extending Thread class by a class to do some “tiny cleaning or logging operation” before the VM halts during some app error and not when terminated by os ( i hope i am saying what u really mean :D ) and after this singleton n caution explaination using reflection -i have come to an conclusion that
    i should request
    you to post an article as soon as possible about “Patterns + Example of Each , Easy Explanation about why and when it can be used and how it works “.
    When i read from different sources i get confused of what is really what and why and when since I’m beginner.
    With your explanation i surely believe i will become a expert for a good cause…
    Thank You

    1. You should not be able to clone an object unless it (or a super class of it) specifically implements Cloneable. So generally it is not needed to handle this explicitly. But IF your singleton is extending from a super-class (which is somewhat unlikely in most of the cases) that exposes a public clone() method, then by all means you should override it and ensure that it throws CloneNotSupportedException.

  28. Hi, Neat post. There’s a problem with your site in internet explorer, would test this IE still is the market leader and a good portion of people will miss your excellent writing because of this problem. ebkdecebkd

    1. Thanks for the feedback. I tested on IE 10 and it seems to work on that version. Appreciate a lot if you could let me know which version of IE that you found this issue.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>