开发者

Is it possible to get the object reference count?

开发者 https://www.devze.com 2023-02-18 10:51 出处:网络
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 (withou

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).


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:

  • Javadoc for WeakReference: http://download.oracle.com/javase/6/docs/api/java/lang/ref/WeakReference.html
  • Javadoc for PhantomReference: http://download.oracle.com/javase/6/docs/api/java/lang/ref/PhantomReference.html
  • A great explanation of weak references: https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references
  • Garbage collector callbacks: http://java.dzone.com/articles/letting-garbage-collector-do-c
  • Garbage collection notification?


Java doesn't offer this option natively as far as I know.

Here you have some guidance on how to do it manually:

http://www.velocityreviews.com/forums/t363649-how-do-i-get-a-reference-count-of-a-object-in-java.html


Java is NOT reference-counting

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

0

精彩评论

暂无评论...
验证码 换一张
取 消