java - 如何找出一个对象有多少引用?

标签 java memory reference jvm

是否有可能和/或容易找出任意对象有多少传入引用?也就是说,有多少对象在引用它。

提前谢谢...

最佳答案

简短的回答是:自己数一数。

另一个 StackOverflow 问题有一些有用的答案和资源

Is it possible to get the object reference count?

更多的谷歌搜索出现了这个页面:http://www.velocityreviews.com/forums/t363649-how-do-i-get-a-reference-count-of-a-object-in-java.html

建议如下:

Java doesn't maintain reference counts. A particular JVM might (I haven't heard of any that does), but if a JVM maintains reference counts that's "a private matter" internal to the JVM's implementation. Java has no construct or utility class to retrieve reference counts, even if the JVM happens to maintain them. (Similarly, the JVM might maintain counters associated with its JIT compiler, but those statistics are not accessible to Java as such.)

If you want to maintain reference counts for your own objects, you'll need to do it manually. It's likely to be an error-prone business:

MyObject ref = null;
try {
    // get a reference, increment counter
    ref = MyObject.getReference(args);
    ...
} finally {
     // decrement counter, promising to drop reference
     if (ref != null) {
         ref.release();
         ref = null;
     }
}

You could establish a self-enforced "protocol" that requires this sort of boilerplate around every use of a MyObject, but it would be clumsy and all too easy to get wrong. And not all situations are as simple as the one above: For example, if you have two references whose lifetimes overlap but don't nest, you can't match them to the lexical scopes of try/finally so neatly.

The collections framework would be pretty much off-limits, or at least very hard to use. When you put a MyObject into a SortedMap, for example, how many references to the MyObject are retained in the Map? Does the answer depend on whether the MyObject is used as key or as value, or as both? It seems to me that your chances of maintaining an accurate count are slim.

Take a step back: WHY do you want these reference counts? What purpose are you trying to fulfil? There may be a better way to achieve your overall strategy than to pursue this very difficult tactic.

关于java - 如何找出一个对象有多少引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397149/

相关文章:

java - 嵌入方法参数表达式是不好的做法吗?

java - 如何从 ResultSet 中获取指定数量的行

arrays - 大型引用文件(800,000 行)。存储在数组中或使用文件句柄

c++ - line 是什么意思?

java - 如何为使用 Mysql 的 Java 应用程序创建 exe 文件

java - 如何从应用程序中准确找到 Java 应用程序使用了多少内存

java - java在使用整数/ double / float 的情况下是否使用内存

ios - 在两个用户之间共享一个全局引用域

c++ - 返回 vector 内对象的引用

java - Spring Security 自定义 RememberMeAuthenticationFilter 没有被解雇