There are two scenarios where it is useful for the hash map to be weak (it seems your second one matches):
One wants to attach information to an object with a known identifier; if the object ceases to exist, the attached information will become meaningless and should also cease. JavaScript supports this script.
It is desirable to combine references to semantically identical objects in order to reduce storage requirements and speed comparisons. Replacing many links with the same large subtrees, for example, with links to the same subtree, can reduce memory usage and execution time. Unfortunately, JavaScript does not support this scenario.
In both cases, the links in the table will be maintained as long as they are useful, and “naturally” become available for collection when they become useless. Unfortunately, instead of implementing separate classes for the two uses defined above, the WeakReference developers made it so that it could be useful for anyone, albeit not very well.
In those cases where the keys define equality for the middle link identifier, WeakHashMap will satisfy the first usage pattern, but the second will be meaningless (the code containing a link to an object that was semantically identical to the stored key, a link to the stored key, and WeakHashMap is not needed to give him). In cases where the keys define some other form of equality, it usually does not make sense for the table query to return anything other than a reference to the saved object, but the only way to avoid saving the saved link is to save the key in use WeakHashMap<TKey,WeakReference<TKey>> and ask the client to get a weak link, extract the key link stored in it and check if it is valid (it can be collected between the moments when WeakHashMap returns WeakReference and the WeakReference time itself is checked).
supercat Sep 02 '14 at 20:37 2014-09-02 20:37
source share