Search code examples
javasingletonclassloader

Singleton class with several different classloaders


E.g I have class Singleton with static field instance:

public class Singleton {

    private static Singleton instance;

    // other code, construct, getters, no matter    
}

I can load this class twice with two different classloaders. How could I avoid it? It is unsafe and dangerous.

Also, if I set instance to null, would it set to null for both classes?

Singleton singleton = Singleton.getInstance();
singleton = null;

Solution

  • If you want a true Singleton across classloaders, then you need a common parent to load the class in question, or you need to specify the classloader yourself.

    Update: From the comment from @Pshemo below a fair bit of the content in the blog below might come directly from a JavaWorld Article. I've left the blog entry in as it may still help someone, but its worth knowing where the content originally came from.

    Original: There is a blog entry that gives you a way to do this" (although I havent tried it!), and it looks fairly reasonable

    As requested below here a code snippet from my link above - I do suggest you visit the blog though for the full context:

    private static Class getClass(String classname) throws ClassNotFoundException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if(classLoader == null) 
            classLoader = Singleton.class.getClassLoader();
          return (classLoader.loadClass(classname));
    }