在浏览 Java 7 API 文档时,我偶然发现了新类 java.lang.ClassValue 具有以下相当少的文档:
延迟地将计算值与(可能)每种类型关联起来。例如,如果动态语言需要为消息发送调用站点遇到的每个类构建消息调度表,则它可以使用 ClassValue 来缓存快速执行消息发送所需的信息,对于每个类遇到类。
任何人都可以更好地解释该类解决的问题以及可能已经使用该类的一些示例代码或开源项目吗?
更新:我仍然对使用这个新类的一些实际源代码或示例感兴趣。
我还在 mlvm-dev 邮件列表上发现了这封邮件,涉及一些内容实施改进。显然,它从使用 WeakHashMap 更改为 java.lang.Class 上的新私有字段,以使其更具可扩展性。
While browsing the Java 7 API documentation I stumbled upon the new class java.lang.ClassValue with the following rather minimal documentation:
Lazily associate a computed value with (potentially) every type. For example, if a dynamic language needs to construct a message dispatch table for each class encountered at a message send call site, it can use a ClassValue
to cache information needed to perform the message send quickly, for each class encountered.
Can anyone give a better explanation of what problem this class solves and perhaps some sample code or open source project that already uses this class?
Update: I'm still interested in some actual source code or examples using this new class.
I also found this mail on the mlvm-dev mailing list concerning some implementation improvements. It was apparently changed from using a WeakHashMap to a new private field on java.lang.Class to make it more scalable.
发布评论
评论(4)
这个类的目的最好的解释是它解决了 Java Bug 6389107
那里在许多用例中,出于某种原因,人们希望本质上拥有一个
Map, T>
,但这会导致各种麻烦,因为然后,Class
对象将无法进行 GC,直到 Map 可以进行 GC。WeakHashMap, T>
不能解决问题,因为T
经常引用该类。上面的错误有更详细的解释,并包含面临此问题的示例项目/代码。
ClassValue 就是这个问题的答案。一种将数据与类关联起来的线程安全的类加载器加载/卸载安全方法。
The best explanation of the purpose of this class is that it solves Java Bug 6389107
There are many use cases where one wants to essentially have a
Map<Class<?>, T>
for some reason, but this causes all sorts of trouble sinceClass
objects will then not be GC-able until the Map is.WeakHashMap<Class<?>, T>
doesn't solve the problem because very frequently,T
references the class.The bug above goes into a much more detailed explanation and contains example projects/code that face this problem.
ClassValue is the answer to this problem. A thread-safe, classloader loading/unloading safe way to associate data with a Class.
其目的是允许将运行时信息添加到任意目标类(参考)。
我认为它更多地针对动态语言程序员。但我不确定它对一般应用程序开发人员有何用处。
最初,该类位于
java.dyn
包中。 此错误显示它已转移到 java.lang。Its purpose it to allow adding runtime information to arbitrary target classes (reference).
I think its targeted more towards dynamic language programmers. I am not sure how it will be useful for general application developers though.
Initially the class was there in the package
java.dyn
. This bug shows it moving to java.lang.ClassValue
缓存有关该类的信息。这是代码的一部分(在 Lucene 5.0
AttributeSource.java
中):ClassValue
cache something about the class.Here is a part of code (at Lucene 5.0
AttributeSource.java
):嗯,它是一个抽象类。我找到了副本< /a>.看看吧。
Well, it is an abstract class. I've found a copy. Have a look at it.