File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Singleton Class and Garbage collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Singleton Class and Garbage collection" Watch "Singleton Class and Garbage collection" New topic

Singleton Class and Garbage collection

Maan Suraj
Ranch Hand

Joined: Dec 20, 2007
Posts: 299
I was going through the below site

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)

Man Suraj
Someone says "Impossible is nothing". The man next him says "Let me see you licking your elbow tip!"
Martin Sergeant

Joined: May 20, 2003
Posts: 24
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)

Maan Suraj
Ranch Hand

Joined: Dec 20, 2007
Posts: 299
Thanks Martin
I agree. Here's the link:
subject: Singleton Class and Garbage collection
It's not a secret anymore!