Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain to me when it is useful to use MapMaker or WeakHashMaps?

I have read many people really like the MapMaker of Google Guava (Collections), however I cannot see any good uses of it.

I have read the javadoc, and it says that it behaves like ConcurrentHashMap. It also says new MapMaker().weakKeys().makeMap() can almost always be used as a drop-in replacement for WeakHashMap.

However, reading the javadocs of ConcurrentHashMap and WeakHashMap makes me wonder when it is useful to use it? It seems to me that you cannot have a guarantee that whatever you put in the map will be there, or have I misunderstood?

like image 848
Shervin Asgari Avatar asked Sep 01 '10 11:09

Shervin Asgari


Video Answer


1 Answers

The thing about MapMaker is that there are many options for the kind of map you build, which enables those maps to serve many purposes.

  • Dirk gives a good example of a use for weak keys.
  • Soft values are useful for caching, as you can cache values in the map without worrying about running out of memory since the system is free to evict entries from the cache if it needs memory.
  • You can choose to have entries expire after a certain amount of time. This is also useful for caching, since you may want certain data cached for a specific period of time before doing an expensive operation to update it.
  • One of my favorite things is making a computing map. A computing map uses a Function<K, V> to automatically retrieve the value associated with a given key if it isn't already in the map. This combines well with soft values and/or expiration times. After an entry is evicted by the map (due to memory demand or expiration), the next time the value associated with that key is requested it will automatically be retrieved and cached in the map once more.
like image 138
ColinD Avatar answered Oct 15 '22 08:10

ColinD