在Java 6中实际使用IdentityHashMap [英] Practical use of IdentityHashMap in Java 6

查看:202
本文介绍了在Java 6中实际使用IdentityHashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

IdentityHashMap的用例

什么可以实际使用在Java 5中引入了IdentityHashMap?

What could be a practical use of the IdentityHashMap introduced in Java 5?

推荐答案

用于向对象添加动态字段。

For adding dynamic fields to objects.

某些语言直接支持动态字段:任何人都可以随时向任何对象添加任何字段。

Some language directly support dynamic fields: anybody can add any field to any object any time.

当您想要将某些信息与对象关联时,这很方便,不可预见由对象设计师。

This is handy when you want to associate some information to objects, unforseenable by object designer.

Java没有真正的动态字段。我们可以通过使用身份地图将对象与某种信息相关联来模拟它。

Java doesn't have real dynamic field. We can simulate it by using an identity map to associate an object to some information of some kind.

WeakHashMap 是更好的目的;它也是一个标识映射,它不会为该对象添加额外的强引用。所以它更接近动态字段概念。

WeakHashMap is better for the purpose; it is an identity map too, and it doesn't add additional strong reference to the object. So it is much closer to the dynamic field concept.

并发是剩下的问题。如果两个线程访问两个不同对象的相同动态字段,则两个线程之间不应存在依赖关系。我们可以通过某种并发的弱hashmap来解决它。然而,与普通现场访问相比,性能不理想。

Concurrency is the remaining problem. If two threads accessing the same dynamic field of two different objects, there shouldn't be dependencies among two threads. We can solve it by some kind of concurrent weak hashmap. However the performance isn't ideal compared to normal field access.

想想 java.lang.ThreadLocal ,为线程添加动态字段;和 java.lang.ClassValue ,将动态字段添加到类中。它们并非绝对必要 - 我们可以通过并发弱映射实现相同的功能。它们存在是出于性能原因。 JDK可以入侵Thread / Class以添加支持以实现更快的查找。

Think about java.lang.ThreadLocal, adding dynamic field to threads; and java.lang.ClassValue, adding dynamic field to classes. They aren't strictly necessary - we can achieve the same thing with concurrent weak maps. They exist for performance reason. JDK can "hack" into Thread/Class to add supports to achieve faster lookup.

这篇关于在Java 6中实际使用IdentityHashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆