Reputation: 603
I'd like to know if there is a way to check how many references a Java object has. As far as I could check the only way to do that is using JVMTI through a JNI interface. Is there a pure Java (without using native libraries) solution to get this information?
We are developing an educational tool for data structure animation(to be used with students implementation of certain algorithms), so it would be very nice if we could check for "released" objects on the most non-intrusive way (I'm trying to avoid forcing the user of this tool to call a method such as objectReleased(objRef)
in order to update the data structure animation for an element removal or something similar).
Upvotes: 38
Views: 29292
Reputation: 8826
And we simply can not get something which does not exist.
See similar Q/A,
which explains why reference recursion does not cause memory-leak:
https://stackoverflow.com/a/72167978/8740349
See Javadoc for PhantomReference
class:
download.oracle.com/javase/6/docs/api/java/lang/ref/PhantomReference.
Also, there is a library which can notify you when an object is garbage collected:
https://sourceforge.net/projects/gcradar
Upvotes: 1
Reputation: 5752
From your description, it seems you care less about the actual count of references than to simply know when an object has been collected. If this is the case, you can use WeakReference
or PhantomReference
to determine when a referenced object is ready for finalization.
See:
WeakReference
: http://download.oracle.com/javase/6/docs/api/java/lang/ref/WeakReference.htmlPhantomReference
: http://download.oracle.com/javase/6/docs/api/java/lang/ref/PhantomReference.htmlUpvotes: 17
Reputation: 1741
Java doesn't offer this option natively as far as I know.
Here you have some guidance on how to do it manually:
Upvotes: 5