pmf
pmf

Reputation: 7749

Tracing garbage collection

I have a problem with interaction with a scripting library and to verify my suspicion I would like to trace when instances of certain classes are GCd (either in Eclipse or JVisualVM or via a command line JVM option). I do't need to discriminate between instances of the classes, since I can restrict the issue to one instance.

Is this possible with a stock VM?

Upvotes: 0

Views: 329

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27115

You could create a collection of java.lang.ref.WeakReference objects, one for each of the objects that you want to watch. You can use the ReferenceQueue mechanism to be notified when the target objects are claimed by the GC.

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200138

I don't think you can do this from the outside. Normally the GC operates such that it takes action to preserve live instances, and the "collection" of garbage is just implicit: memory regions are simply determined to be available for allocation.

The closest you can get is being notified when an object has reached the finalized state, which is still before it is actually collected. To that end you can add some code which will create PhantomReferences to your objects of interest and register them with a ReferenceQueue. You can monitor the queue for finalized objects. Note that there are a lot of "at that time or at some later time" kind of phrases in the specification of these mechanisms; you can't count on realtime accuracy.

Also note that the above mechanism itself will disturb the observed system and it will not act the same as when there are no phantom references to track.

Upvotes: 3

Related Questions