Cache.asMap().put() 或 Cache.put()

Cache.asMap().put() or Cache.put()

我正在使用 Google-番石榴缓存。定义为:

Cache<String, String> myCache= CacheBuilder.newBuilder().maximumSize(100).build();  

当我使用 get/put 进行地图操作时:

  myCache.asMap().put("someString", "someString");
  String someValueFromCache = myCache.asMap().get("someString");

我想知道如果我按照以下方式使用它,即不将其用作地图,是否会有任何优化或任何类型的差异:

  myCache.put("someString", "someString");
  String someValueFromCache = myCache.get("someString");

来自番石榴缓存文档:https://github.com/google/guava/wiki/CachesExplained#inserted-directly

Values may be inserted into the cache directly with cache.put(key, value). This overwrites any previous entry in the cache for the specified key. Changes can also be made to a cache using any of the ConcurrentMap methods exposed by the Cache.asMap() view. Note that no method on the asMap view will ever cause entries to be automatically loaded into the cache. Further, the atomic operations on that view operate outside the scope of automatic cache loading, so Cache.get(K, Callable) should always be preferred over Cache.asMap().putIfAbsent in caches which load values using either CacheLoader or Callable.

认为您不应该使用 asMap() 视图来修改缓存。

除了@rdas 的回答,还有一些注意事项:

  1. 如果你不使用 LoadingCache(如你的例子),两者之间真的没有区别(好吧,使用 .asMap() 更混乱),有时你想要/有使用 (Concurrent)Map 接口实现兼容性,在这种情况下使用 .asMap() 是完全没问题的。
  2. 如果您想访问/迭代所有键/​​值,Cache 接口不提供此类方法,但 Map 提供 - 请参阅 .
  3. 还有其他区别(实际上在文档中,但我很难学到):通过 .asMap() 视图修改 Cache 不会更新 CacheStats, if you have them enabled via CacheBuilder#recordStats().