如何从 Guava 17 替换 Guava new MapMaker().softValues().makeMap()

How do I replace Guava new MapMaker().softValues().makeMap() from Guava 17

我使用的是 Guava 17.0

private static final ConcurrentMap<String, Buffered> imageMap =
        new MapMaker().softValues().makeMap();

刚更新到 Guava 27,发现 softValues() 已经移到 CacheBuilder 所以我可以

CacheBuilder.newBuilder().softValues()

但是没有makeMap()方法,所以我用什么代替。

参见MapMakerMigration on Wiki:

All caching related methods on MapMaker have been deprecated in favor of similar methods in CacheBuilder, and are scheduled for upcoming deletion. (...)

Most MapMaker use cases should be migrated to either CacheBuilder or AtomicLongMap. Specifically, cases when MapMaker is used to construct maps with AtomicLong values should generally be migrated to AtomicLongMap. Other cases where MapMaker caching functionality is used (including all uses of MapMaker.makeComputingMap(Function)) should be migrated to CacheBuilder.

所以问题是:你真的需要使用ConcurrentMap接口吗?如果是,请使用 asMap() 视图,对于非计算地图应该具有相同的功能:

Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to the map directly affect the cache.

在你的情况下,这将是:

private static final Cache<String, Buffered> IMAGE_CACHE = CacheBuilder.newBuilder()
    .softValues()
    .build();

然后使用 CACHE.asMap() 或使用 .asMap() 以及字段的显式类型参数:

private static final ConcurrentMap<String, Buffered> IMAGE_MAP =
    CacheBuilder.newBuilder()
        .softValues()
        .<String, Buffered>build()
        .asMap();