views:

479

answers:

3

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

A: 

You could use a ConcurrentHashMap<Class, WeakReference<Object>>, but you'd need to write additional boilerplate code to read and write from the data structure.

Matthew
That won't work as the entries to the map itself will never GC.
Will Hartung
+1  A: 

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."

objects
+8  A: 

Google Collections' MapMaker class allows you to do this easily. Check it out, the project is awesome...

Steven Schlansker
Wow, that `MapMaker` class is very impressive. It does way more than I'd normally expect of a single class, so it's really a facade to a whole slew of things that can probably be composed in different ways. The `com.google.common.base` package is also nice.
seh
Excellent! Thanks for the pointer, Steven!
Nikita