I was designing the below singleton class, and I am aware of that where my singleton can be broken
public class SingletonObject {
private static SingletonObject ref;
private SingletonObject () //private constructor
{ }
public static synchronized SingletonObject getSingletonObject()
{
if (ref == null)
ref = new SingletonObject();
return ref;
}
public Object clone() throws CloneNotSupportedException
{throw new CloneNotSupportedException ();
}
}
the following url already suggest where singleton can be broken cracking singleton with other ways but my query is that as suggested in this url that singleton can be broken by class loader also same class could be loaded by two different class loaders, as such, you could create two instances of your singleton class by simply invoking its getInstance() method in a class loaded by two different class loaders. This approach would work without having to resort to violating the private constructor.
ClassLoader cl1 = new URLClassLoader(new URL[]{"singleton.jar"}, null);
ClassLoader cl2 = new URLClassLoader(new URL[]{"singleton.jar"}, null);
Class<?> singClass1 = cl1.loadClass("hacking.Singleton");
Class<?> singClass2 = cl2.loadClass("hacking.Singleton");
//...
Method getInstance1 = singClass1.getDeclaredMethod("getInstance", ...);
Method getInstance2 = singClass2.getDeclaredMethod("getInstance", ...);
//...
Object singleton1 = getInstance1.invoke(null);
Object singleton2 = getInstance2.invoke(null);
Please advise what measure should be taken to avoid this also.