Will the Guava <K, Semaphore> cache with weak Values ​​() be thread safe?

I need a key lock mechanism to protect critical key-related partitions.

Although ConcurrentMap<K, Semaphore> enough for concurrency, I also don’t want the card to accumulate old keys and grow indefinitely.

Ideally, the data structure will ultimately (or immediately after) free up memory used for keys for which locks are not used.

I seem to think that Guava Cache built with weakValues() will do the trick:

 private static final LoadingCache<K, Semaphore> KEY_MUTEX = CacheBuilder.newBuilder() .weakValues() .build(new CacheLoader<K, Semaphore>() { @Override public Semaphore load(K key) throws Exception { return new Semaphore(1); } }); 

Are there reasons why this might not provide a sufficient concurrency control?

Or the reasons why this may not lead to the fact that unused vapors will collect garbage?

+6
source share
1 answer

Yes it will work.

There is also a data structure designed more or less for this use case: Striped .

+3
source

All Articles