Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there java.util.concurrent equivalent for WeakHashMap?

Can the following piece of code be rewritten w/o using Collections.synchronizedMap() yet maintaining correctness at concurrency?

Collections.synchronizedMap(new WeakHashMap<Class, Object>());

i.e. is there something from java.util.concurrent one can use instead? Note that merely replacing with

new ConcurrentHashMap<Class, Object>(new WeakHashMap<Class, Object>()));

obviously won't work

like image 257
Nikita Avatar asked Feb 13 '10 00:02

Nikita


3 Answers

Guava's CacheBuilder class allows you to do this easily.

CacheBuilder.newBuilder().weakKeys().build()

Note that this changes key equality semantics to be == instead of .equals() which will not matter in your case of using Class instances but is a potential pitfall.

like image 115
Steven Schlansker Avatar answered Oct 21 '22 13:10

Steven Schlansker


I don't believe there is. In fact the javadoc suggests using Collections.synchronizedMap()

"Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method."

like image 22
objects Avatar answered Oct 21 '22 12:10

objects


Cafeine is a popular competitor of Guava cache.

- keys automatically wrapped in weak references
- values automatically wrapped in weak or soft references

usage:

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
 .weakKeys()
 .weakValues()
 .build(key -> createExpensiveGraph(key));
like image 2
Waldemar Wosiński Avatar answered Oct 21 '22 13:10

Waldemar Wosiński