Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 345
antak Avatar asked Feb 15 '16 13:02

antak


1 Answers

Yes, that'd work.

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

like image 104
Louis Wasserman Avatar answered Sep 18 '22 11:09

Louis Wasserman