是否可以获取对象引用计数?

时间:2022-02-04 16:53:54

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?

我想知道是否有办法检查Java对象有多少引用。据我所知,唯一的方法就是通过JNI接口使用JVMTI。是否有纯Java(不使用本机库)解决方案来获取此信息?

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

我们正在开发一种用于数据结构动画的教育工具(与学生实现某些算法一起使用),所以如果我们能够以最非侵入性的方式检查“已发布”的对象,那将是非常好的(我试图避免强迫此工具的用户调用ObjectReleased(objRef)等方法来更新数据结构动画以删除元素或类似的东西

2 个解决方案

#1


12  

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.

根据您的描述,您似乎不太关心引用的实际数量,而只关心何时收集对象。如果是这种情况,您可以使用WeakReference或PhantomReference来确定引用的对象何时可以完成。

See:

Hope this helps.

希望这可以帮助。

#2


5  

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

据我所知,Java本身不提供此选项。

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

#1


12  

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.

根据您的描述,您似乎不太关心引用的实际数量,而只关心何时收集对象。如果是这种情况,您可以使用WeakReference或PhantomReference来确定引用的对象何时可以完成。

See:

Hope this helps.

希望这可以帮助。

#2


5  

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

据我所知,Java本身不提供此选项。

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