Guava 的 Cache<K, Semaphore> with weakValues() 会是线程安全的吗?

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

我需要一个键锁定机制来保护键绑定临界区。

虽然 ConcurrentMap<K, Semaphore> 足以满足并发性,但我也不希望地图累积旧键并无限增长。

理想情况下,数据结构最终(或之后立即)释放用于未使用锁的键的内存。

我觉得用 weakValues() 构建的 Guava Cache 可以解决问题:

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);
            }
        });

这可能无法提供足够的并发控制,是否有任何原因?

或者这可能不会导致未使用的对被垃圾收集的原因?

是的,那行得通。

还有一个或多或少为这个用例设计的数据结构:Striped