Guava Cache的读取锁定是否免费 [英] Is Guava Cache's read lock free

查看:135
本文介绍了Guava Cache的读取锁定是否免费的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Guava的缓存,并将 concurrencyLevel 设置为 1 ,以便最大程度地利用容量。驱逐有关。以下是我的代码:

I am using Guava's Cache and have set concurrencyLevel to 1 so the maximum capacity is utilized w.r.t. eviction is concerned. Following is my code:

CacheBuilder.newBuilder()
                    .maximumWeight(maxWeight)
                    .concurrencyLevel(1)
                    .expireAfterWrite(expireDuration, TimeUnit.MINUTES)
                    .removalListener(new RemovalListener<K, V>() {
                        @Override
                        public void onRemoval(RemovalNotification<K, V> removalNotification) {
                            log.warn(removalMsg + removalNotification.getKey());
                        }
                    })
                    .weigher(weigher)
                    .build();

concurrencyLevel 这样说:


指导更新操作之间允许的并发。用作内部大小调整的提示
。该表在内部进行了分区,以尝试
允许指定数量的并发更新而没有
竞争...

Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The table is internally partitioned to try to permit the indicated number of concurrent updates without contention...

因此,我假设 concurrencyLevel 仅对 update操作起作用即使使用 concurrencyLevel(1),读取也是无锁的。

And hence I was assuming that the concurrencyLevel plays a role only for update operations and the READs are Lock Free even with concurrencyLevel(1).

我的假设正确吗?

编辑:
我看着Guava Caching代码,它看起来就像我以为 READs是无锁的的假设是正确的。在 get(K,Callable)的情况下,它最初尝试获取不带锁的值,并且如果指定键的条目为null或仅已过期,则它将继续锁定的获取或加载。如果我错了,请纠正我。

I looked at the Guava Caching codeand it looks like my assumption that READs are lock free is correct. In case of get(K, Callable) initially it tries to get the value without lock and if the entry for the specified key is either null or has expired only then it goes for a locked Get or Load. Please Correct me if I am wrong here.

推荐答案

您可以自己看一下代码。大部分相关内容位于 LocalCache

You can take a look at the code yourself. Most of the relevant stuff is in LocalCache.

无论如何,根据我的理解(我不是专家(在缓存中),读取(在非 LoadingCache 上)通常应该是无锁的(在 LoadingCache 上)这取决于他们是否需要加载值,在这种情况下,读操作也将变成写操作)。在某些代码路径中,使用 tryLock()来获取锁,但是由于它是 tryLock(),因此没有读取线程

Anyway, from my understanding (I'm not an expert on the cache stuff), reads (on a non-LoadingCache) should generally be lock-free (on a LoadingCache it depends on whether they need to load a value, in which case the read becomes a write too). In some code paths tryLock() is used to acquire a lock, but since it's tryLock() no reading threads should block if the lock is held I don't think.

编辑:

来自中的注释:


段维护一个条目列表始终保持一致状态,因此无需锁定即可读取。

Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so can be read without locking.

concurrencyLevel(1)当前表示1个细分。)

这篇关于Guava Cache的读取锁定是否免费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆