[concurrency-interest] synchronized maps

Dhanji R. Prasanna dhanji at gmail.com
Sun Aug 26 23:13:56 EDT 2007


I have a JIT-style cache implemented as a HashMap. When client code requests
a key, it looks for an entry and if there is nothing, "compiles" and stashes
a value for that key. Currently, I am using a Collections.synchronizedMap()
wrapper over a j.u.HM. Since I am assured that the value for a key ("natural
value") is always the same, I don't really care if multiple threads compile
and overwrite the same key concurrently.

Am I correct in assuming that using a ConcurrentMap.putIfAbsent() will be
faster in my case (so I can discard concurrently compiled values that are
"later" than the first-put) than a straightforward synchronized overwrite
(multiple puts)?

Assuming of course, that the cost of creating the value is negligible
compared to the cost of locking the entire cache-get method as number of
threads increase... the cache-get method exposed to client code right now is
(deliberately) unsynchronized.

I have another minor question regarding j.u.HM. I publish an unmodifiable
(pre-constructed) HM instance to a final member of an object, is it safe to
assume that leaving the map unsynchronized for multiple threads invoking
get() is ok (i.e. is there any kind of internal optimization after the

Thanks in advance,

-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20070827/7a65dc14/attachment.html 

More information about the Concurrency-interest mailing list