Why does ConcurrentLruCache in Spring still use thread-safe maps and queues instead of ordinary maps and queues even when read-write lock are used?

Viewed 206

spring-framework/ConcurrentLruCache.java at main · spring-projects/spring-framework · GitHub

Update

Because there may be multiple readers writing to the queue concurrently, the queue must use a thread-safe data structure, and the put operation of the cache is done in the write lock, can the implementation of the cache be replaced with a HashMap? Because the get method of ConcurrentHashMap is implemented without lock.

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. (More formally, an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key reporting the updated value.)

From ConcurrentHashMap (Java Platform SE 8 )

1 Answers

Take a closer look at the get method. The choices made to maximize the number of concurrent readers mean the code doesn't enforce the exclusion needed to be able to use non-threadsafe collections.

The cache is accessed without any lock held. The authors want to avoid having to acquire a lock just to read from the cache.

The queue is accessed with a read lock, so there can be multiple concurrent readers. That requires the queue implementation to be threadsafe.

(Of course if the code used a read lock to read from the cache, then the same issue with multiple readers would be true for the cache as well.)

For the question about using hashmap instead of CHM, part of what you get from using locks is memory visibility. If you use HashMap then when the cache is updated the get method also needs to lock in order to avoid all the issues around insufficiently-synchronized code like JIT optimizations and reorderings.

Related