Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Weak Hash Map - Need to remove entry based on weakness of value, not key

So the Java WeakHashMap lets one create a map whose entries are removed if its keys become weak. But how can I create a Map whose entries are removed when the values in the map become weak? The reason I want to use a map is as a Global Hash Table which keeps track of objects according to their ID's.

ID --->  Object Address

Key ---> Value

(Where ID is a text string)

I want key-value pairs to be removed when the object addresses become weak, not the Strings that point to them. Anyone any thoughts on this?

like image 434
Binaromong Avatar asked Apr 14 '11 16:04

Binaromong


People also ask

What is true about a WeakHashMap garbage collector will automatically remove the entry from it?

An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed.

How do I remove a value from a HashMap?

HashMap remove() Method in Java HashMap. remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Parameters: The method takes one parameter key whose mapping is to be removed from the Map.

What if HashMap does not contain key?

If you try to get something from the HashMap for a key that is not present in the map, the map returns null . That is true for any key you try to get from an empty map.

What is true about a weak HashMap?

WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap.


1 Answers

Such a map is supported, for example, in Guava:

Map<..., ...> m = new MapMaker().weakValues().makeMap();
like image 61
axtavt Avatar answered Oct 21 '22 10:10

axtavt