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;
This is a hack misusing the fact that
Properties
extendsMap
, an old unfortunate design decision.This could be made parametrized, but then the initialization would be lazy and go to
getSingleton()
.Properties
isHashtable
-based, so it is thread safe (as per the documentation). So one could useprops.computeIfAbsent()
. But I like it this way more.Also read here: Scope of the Java System Properties
I just wrote it and there is a chance there's something I overlooked that would prevent this from working.
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: