Code Trivia: Enforcing Java Singletons is Very Hard

Here is my response to an article posted by Per-Ake Minborg on Javalobby:

Article link: Enforcing Java Singletons is Very Hard

package scratch;

 * A perfect implementation of a singleton.

* This example assumes that the binary class file will not be modified, * otherwise all best are off, if the classfile integrity is compromised and * contents rewritten. Also assumes that the adversary will have full access to * the source of this file and attempt any trick in the book. Also we make * the constructor and instance variable public to make it easier to take shots * at the implementation. Its is well known that reflection can defeat these * so called, security features of java. *

* *

* The constructor relies on a custom class loader and uses the state of a * private class Lock as a determining flag. If the inner Lock * class has not been previously loaded by the classloader, the * Singleton instance is allowed to be created. However, the * constructor loads the lock class and thus prevents another instance of * Singleton to be every created as long as the class is not garbage collected. *

* *

* The static singleton variable can be nulled out, and thus the entire * singleton corrupted, but a secondary instance can not be created, at least * not very easily even when using reflection. *

* *

* As with any type of language and code anything and everything can always be * defeated by a determined programmer. *

* * @author Sly Technologies Inc. * @author Mark Bednarczyk */ public final class Singleton { public final static class SingletonClassLoader extends ClassLoader { private static final SingletonClassLoader loader = new SingletonClassLoader(); public SingletonClassLoader() { super(Singleton.class.getClassLoader()); } public static void ensureSingleInvocation() throws IllegalStateException { try { if (loader.findLoadedClass(Lock.class.getName()) != null) { throw new IllegalStateException( "singleton already allocated"); } Class.forName(Lock.class.getName(), true, loader); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } private static class Lock { // Empty on purpose } }; public final static Singleton singleton; static { singleton = new Singleton(); } /** * This constructor allows a single instantiation of Singleton. */ public Singleton() { SingletonClassLoader.ensureSingleInvocation(); } public static Singleton newInstance() { return singleton; } }