Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton testing  RSS feed

 
Charles McGuire
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Charles,

Eclipse will run each application in its own JVM process. Therefore, ClassA and ClassB will indeed be loaded by separate classloaders, hence the behavior you've observed. The main() method invocation is part of the JVM start-up procedure, so if you're starting your program execution from a main() method, that's a pretty good clue that you have a new JVM process.
 
Charles McGuire
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Kelvin. I didn't know Eclipse did that, but it makes perfect sense.

Now, how do I repair my desk where my forehead kept bashing it for hours on Friday?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!