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)
-
You could grep your code for class's name and see if you find instances where it is being used. Some IDEs have tools that can find references to classes. – YWE Sep 25 '10 at 22:06
-
Why do you put your answer in the comment box? – Erick Robertson Sep 25 '10 at 22:16
-
1Be careful! Your class could be in use by reflection. That's impossible to be detected automatically, because the class name could be constructed at runtime (no explicit string in your source code). – tangens Sep 25 '10 at 22:34
-
possible duplicate of [How to find unused/dead code in java projects](http://stackoverflow.com/questions/162551/how-to-find-unused-dead-code-in-java-projects) – Pascal Thivent Sep 25 '10 at 23:00
-
3The OP commented below that he actually wants to know when an object in a JVM is no longer in use, not a class in an application. Unfortunately, nobody caught this meaning and everyone answered it the wrong way. I have flagged this question for moderator attention - I don't know what to do in this situation. I don't want to edit the question because it will invalidate all of the answers. – Erick Robertson Sep 30 '10 at 12:47
-
@user330281: Do you need to know when a **class** is no longer in use, or when a particular **object** is no longer in use? Please edit your question to clarify. – Bill the Lizard Sep 30 '10 at 13:16
-
Wow, this many people misunderstood... was the question edited? – Tony Ennis Sep 30 '10 at 20:37
-
Peter Lawrey just edited it to correct the meaning. @Bill: see the comment the OP asked in my answer. – Erick Robertson Oct 01 '10 at 16:18
3 Answers
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.

- 525,659
- 79
- 751
- 1,130
in Eclipse you can right-click your class, and select References > Project

- 588,226
- 146
- 1,060
- 1,140
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.

- 266,786
- 75
- 396
- 414