gpt4 book ai didi

java - 使用 CacheBuilder 的缓存作为 Map

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:57:00 24 4
gpt4 key购买 nike

我目前在我的应用程序中使用 ConcurrentHashMap,但我需要添加在超时期限后有效地使条目过期的功能 (expireAfterWrite),并在删除条目时通知删除监听器。

我看到 CacheBuilder 可以提供我需要的东西,但我犹豫是否要使用它,因为我需要的是 map ,而不是缓存。我这样说( map 和缓存之间的区别)是因为 guava 缓存文档说明了这一点

Generally, the Guava caching utilities are applicable whenever:

  • You are willing to spend some memory to improve speed.
  • You expect that keys will sometimes get queried more than once.
  • Your application would, in principle, work if every value was evicted from the cache immediately -- but you're trying to reduce duplicated work.

特别是第三个要点在我的申请中不合适。我将值存储在以后要检索的 map /缓存中(直到其到期)。此外,我的 key 通常只被查询一两次,查看缓存优势的次数不多。所以你看我的要求是 map ,而不是某种意义上的缓存。使用 CacheBuilder 作为映射来存储将在写入后过期并提供 removalListener 功能的值仍然是个好主意吗?有没有人足够了解 CacheBuilder 实现的内部结构来提供建议?

最佳答案

编辑: 当然 MapMaker 缓存功能已弃用,取而代之的是 CacheBuilder , 我的错。不要犹豫,使用它:

Cache<Key, Graph> graphs = CacheBuilder.newBuilder()
.concurrencyLevel(4) // read docs for more details
.expireAfterWrite(yourExpireTime, TimeUnit.MINUTES)
.build();

然后使用 Cache#asMap()如果您希望将其视为 ConcurrentMap。

使用 Guava 的另一个实用程序 - MapMaker .来自文档:

A builder of ConcurrentMap instances having any combination of the following features:

  • keys or values automatically wrapped in weak or soft references
  • least-recently-used eviction when a maximum size is exceeded
  • time-based expiration of entries, measured since last access or last write
  • notification of evicted (or otherwise removed) entries
  • on-demand computation of values for keys not already present

(...)

The returned map is implemented as a hash table with similar performance characteristics to ConcurrentHashMap. It supports all optional operations of the ConcurrentMap interface. It does not permit null keys or values.

关于java - 使用 CacheBuilder 的缓存作为 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11143528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com