Possible Duplicate:
Use cases for IdentityHashMap
What could be a practical use of the IdentityHashMap introduced in Java 5?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 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.
WeakHashMapis 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.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.
Think about
java.lang.ThreadLocal, adding dynamic field to threads; andjava.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.