ConcurrentHashMap::computeIfAbsent and synchronized

Alan Bateman Alan.Bateman at oracle.com
Fri Jan 20 12:49:10 UTC 2023


On 20/01/2023 06:22, mikmoila wrote:
> Hi.
>
> As often mentioned in this mailing-list a feedback about 
> preview/incubator features is appreciated, so here's one:
>
> I was experimenting with a caching system utilising ConcurrentHashMap 
> as cache store and Structured Concurrency API for refreshing the 
> entries from multiple sources ( StructuredTaskScope.ShutdownOnSuccess 
> ). The idea was to make http-requests for getting the fresh values but 
> the first implementation simply uses UUID::randomUUID for simulating that.
> I noticed that the programs halts In a test case where "N" concurrent 
> calls (where "N" >= number of cpu cores) running on virtual threads 
> end-up calling the ConcurrentHashMap::computeIfAbsent for the same 
> (non-existing) key.
>
> "-Djdk.tracePinnedThreads=full" reveals that there is a pinned carrier 
> thread:
> java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1708) 
> <== monitors:1
>
> The documentation ( 
> https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html#computeIfAbsent(K,java.util.function.Function) 
> ) says:
>
>   "Some attempted update operations on this map by other threads may 
> be blocked while computation is in progress, so the computation should 
> be short and simple."
>
> This is clear but I still found it as a surprise that it uses 
> synchronized instead of "virtual-thread friendly" constructs.
>
Thanks for taking time to send feedback.

The CHM.computeXXX methods work okay from virtual threads when the 
mapping function does something short/simple. The quality of 
implementation issue is when they do something long running, like block 
on I/O, in which case you get disappointing performance, as you would 
with platform threads too.

I think Doug Lea has looked at the synchronization in this code a few 
times. Separately, we expect the pinning issus will go away but it's not 
a trivial project and requires work in several areas.

-Alan




More information about the loom-dev mailing list