posted 20 years ago
Hi Chhota,
Interesting question. According to me, there will be two instances of a singleton in one JVM if the singleton class was loaded more than once by different classloaders. Now, here is the catch - "only if the SINGLETON CLASS is loaded by different class loaders"...
First I would explain my theory about why there would be two instances of singleton if the singleton class is loaded by two different classloaders and then I would explain in detail about the "catch" I mentioned above.
Part-1]
--------
Here is my theory for first part,
- Singleton has a static method to obtain an object ref
- Static methods are at the class level
- Hence if a class is twice there in memory we have two copies of those static methods and the static private variable (as per the singleton impl)
Thus when we call classname.getInstance(), it will check in corresponding private variable to see if its null or not (according to the singleton logic) so essentially it will allow us to create two instances of the object in memory...
Part-2] What about the "catch"?
--------------------------------
NOW, as in your question, if the class loaded by different class loaders refers to singleton what happens? Here, we have to see if the singleton class is also loaded by the corresponding class loaders or not.
For e.g. we have a singleton class S and a class X using S.
AND Class X is loaded twice by two different classloaders - CL1, CL2.
If S is always loaded by some other class loader CL3 (this might happen due to some hierarchy of classloaders etc you know) then it would mean that- no matter that X is loaded twice (once by CL1 and then CL2), S would be always loaded once (that is by CL3) AND hence there would be only one instance of singelton ever created.
But if the S is also loaded by CL1 or CL2 correspondingly then, I would say that "there would be two instances of S" (one from CL1, another from CL2).
Hopefully I am able to express myself.
Regards
Maulin