This is an easy question, but it takes a bit of explaining:
I have three classes, call them SingletonClass, ClassA and ClassB. The SingletonClass has a System.out.println statement in the constructor so I can see when it is being created.
In
testing, I call ClassA which calls the SingletonClass. I get my expected results. One of the things it does is spit out a toString() of itself to the console of itself. (This way I can visually compare it when referenced later.)
Then I execute ClassB, which calls upon the SingletonClass to get an instance of what should be an already created object. But the constructor of SingletonClass fires! In ClassB, also prints a toString() of the SingletonClass and see that it is not the same object.
Pouring over my Singleton code, I'm sure it's right. I mean, a Singleton is such a simplest
pattern.
So then I create a fourth class, a throwaway class just for testing, called TopClass. It calls ClassA first (which calls the SingletonClass), then it calls ClassB. The constructor does NOT fire again when ClassB is called, and the Singleton object is the same - so in this scenario it works.
So now I'm thinking that in my first test, where I call ClassA and ClassB separately (using the "Run As
Java Application" from Eclipse), that the SingletonClass object is being garbage collected before I manually run ClassB.
If true, there is something about manually running Java programs with "public static void main(
String[] args)" methods that I have yet to learn. Running them this way, it's as if they are running in two different JVM's or classloaders.
Can anyone shed any light here?