1 of 1 people found this helpful
John O'Hara wrote:
I am trying to write a rule that will fire when an object (of a particular class) is dereferenced and becomes available for GC. The object may be set to null, or removed from a collection. I have been looking at writing a rule that transforms a class in the JVM (openjdk hotspot) to capture this scenario, but have not found anything so far.
Let's start by noting that you can only use Byteman to inject behaviour into Java code. So, your options for handling Object reclamation are essentially limited to the places where the JVM lets Java code know that an object has been reclaimed by the GC and is ready for reuse i.e. finalizer methods. So, if the class you are interested in overrides method Object.finalize() then you can inject a rule into its implementation and it will be triggered when the object's storage is (probably) going to be reclaimed. But there are caveats here to take note of:
- the object will very likely be finalized quite some time after all references to it are dropped (the wait intreval will be at least until after the next minor GC, maybe even the next major GC later and maybe even longer)
- if the finalizer code or the Byteman rule it triggers retains a reference to the object then its storage will not be made available for reuse even though the object has been finalized
- even if you don't retain a reference you will require yet another GC cycle after the finalizer has run before the storage will be released
- finalizers suck and they make your GC sucky because you have to process every finalized object you allocate so don't use them unless you have to and don't ever use them for frequently allocated classes.
- did I mention that finalizers really make your GC suck? oh yes, I did
If that doesn't make you give up now then my final advice is give up now. GCs don't actually care about when the last reference to an object gets dropped. They only care about reusing storage. Mostly, they only need to know which objects are referenced and only at specific points during the GC cycle. So, nothing in the JVM (or indeed most other VMs) -- let alone in the Java runtime -- is going to give an answer to your question.
Thank you for your quick and thorough response.
I am trying to trace a resource issue where objects are being dereferenced without system resources being released. I have used finalizers to track down instances where objects are being GC'd with system resources still held by the object. Although that confirms the issues i am seeing, it does nothing to tell me where (or why) it was dereferenced, as you mentioned in point 1) .
I thought it was a long shot, but a question worth asking nonetheless.
Once again, thank you for your response