Search code examples
javamultithreadingguavaweak-references

Would Guava's Cache<K, Semaphore> with weakValues() be thread safe?


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?


Solution

  • Yes, that'd work.

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