I need a per-key locking mechanism for protecting key-bound critical sections.
Although a ConcurrentMap<K, Semaphore>
would suffice for concurrency, I also don't want the map to accumulate old keys and grow indefinitely.
Ideally, the data structure will eventually (or straight after) release the memory used for keys to which the locks are unused.
I'm kind of thinking Guava's Cache
built with weakValues()
would 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 any reasons why this might not provide sufficient concurrency control?
Or reasons why this might not result in unused pairs being garbage collected?
Yes, that'd work.
There's also a data structure designed more or less for this use case: Striped
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With