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

Singleton Class and Garbage collection

 
Maan Suraj
Ranch Hand
Posts: 299
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was going through the below site
http://java.sun.com/developer/technicalArticles/Programming/singletons/

and i was little bit confused about one of the points mentioned there

Singleton Classes Destroyed by Garbage Collection, then Reloaded
When a Singleton class is garbage-collected and then reloaded, a new Singleton instance is created. Any class can be garbage-collected when no other object holds reference to the class or its instances
.

If no object holds a reference to the Singleton object, then the Singleton class may disappear, later to be reloaded when the Singleton is again needed. In that case, a new Singleton object will be created. Any static or instance fields saved for the object will be lost and reinitialized.



I understand that GC collects the unreferenced objects on the heap.However, what about the classes? Why are classes GarbageCollected? I mean we can create the objects of a class at any time...right .....(things in first quote is not very clear to me)

 
Martin Sergeant
Greenhorn
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would be a waste of memory to hold information about all java classes during a program, so I guess that classes are loaded into memory
when an instance of that class is first created or when a static member is accessed .When there are no objects of that class left
and if there are no references to static data of that class, I guess the class information will be removed from memory (garbage collection)
A potential problem with singletons is that if no object holds a a reference to the Singleton object then then the object and class
will be garbage collected. The next call to getSingleton() will cause the class to reload and a new instance of the Singleton will have to be created
, any data previously associated with it will have been lost. Hence within a program all calls to getSingleton() may not return exactly the same object.

However I shouldn't worry too much about it.
I don't think the Singleton pattern nor Class garbage collection are on the exam (Objective 5.1/5.2 and 7.4)

Martin
 
Maan Suraj
Ranch Hand
Posts: 299
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Martin
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic