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)
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.