How could I figure out that an object(or objects of a class) is/are not in use and ready to be collected by GC. or how could i get to know that object has no reference while the application is running. (before it gets GCed)
views:
130answers:
3in Eclipse you can right-click your class, and select References > Project
I use the UCDetector (Unnecessary Code Detector) Eclipse plugin. It will show you public classes, methods or fields which have no references, and allow you to delete them easily.
I assume you mean detecting an object is no longer in use at run time, rather than something you can check staticly.
The simplest way to be notified that an object is about to be GCed is to override the finalize() method. Note: you have to be careful what you do in this method. e.g. It is single threaded and blocking will result in no objects being cleaned up.
Another approach is to use Weak or Soft References and monitor a ReferenceQueue. This is a way to monitor when an object has been detected as available to be cleaned up. See the source for WeakHashMap for an example.
Note: there is no simple way to detect an object is no longer in use without a GC, and if you don't have a GC for a long time, you have no way of knowing in the meantime.