guava:LoadingCache缓存机制支持弱引用(WeakReference)

前几天写过一篇博客:《java:基于弱引用(WeakReference)的FunctionCached实现》介绍在guava 缓存机制上实在基于弱引用(WeakReference)的缓存机制。

当时还挺得意,然而在我因为其他原因又进一步看了guava 缓存机制相关的代码后,才知道guava 缓存机制本身就支持弱引用(WeakReference)模式,还非常方便,根本不需要再发明一遍轮子。唉,这走的弯路又是吃了不看文档的亏。
com.google.common.cache.CacheBuilder.weakValues()方法就是在构建一个缓存实例时指定弱引用(WeakReference)模式,以下是方法简要说明:

指定存储在缓存中的每个值(而不是键)都应封装在WeakReference中(默认情况下,使用强引用)。

弱值一旦是弱可访问的,就会被垃圾收集。

java 复制代码
  /**
   * Specifies that each value (not key) stored in the cache should be wrapped in a
   * {@link WeakReference} (by default, strong references are used).
   *
   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
   * candidate for caching; consider {@link #softValues} instead.
   *
   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
   * comparison to determine equality of values.
   *
   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
   * but will never be visible to read or write operations; such entries are cleaned up as part of
   * the routine maintenance described in the class javadoc.
   *
   * @return this {@code CacheBuilder} instance (for chaining)
   * @throws IllegalStateException if the value strength was already set
   */
  @GwtIncompatible // java.lang.ref.WeakReference
  public CacheBuilder<K, V> weakValues() {
    return setValueStrength(Strength.WEAK);
  }

所以要创建弱引用(WeakReference)模式的缓存对象就很简单:

java 复制代码
	@Test
	public void test2() {
		LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
				/** 指定值存储使用弱引用(WeakReference)模式 */
				.weakValues()
				.build(new CacheLoader<String, Integer>(){

					@Override
					public Integer load(String key) throws Exception {
						/** 只会输出一次 */
						System.out.printf("parse:%s", key);
						return Integer.parseInt(key);
					}});
		cache.getUnchecked("3333");
		cache.getUnchecked("3333");
		cache.getUnchecked("3333");
	}

CacheBuilder不仅支持弱引用模式,还支持软引用(SoftReference),即softValues()方法

进一步,guava缓存机制的键存储也支持弱引用和软引用模式(对应CacheBuilderweakKeys()softKeys()方法)

更多说明参见guava的WIKI(https://github.com/google/guava/wiki)或源码。

参考资料

《Reference-based Eviction》

相关推荐
东方芷兰12 分钟前
JavaWeb 课堂笔记 —— 08 请求响应
xml·java·笔记·spring·tomcat·html·idea
菜鸟起航ing22 分钟前
【Java面试系列】Spring Cloud微服务架构中的分布式事务实现与性能优化详解 - 3-5年Java开发必备知识
java·spring cloud·微服务·面试·分布式事务
Java手札27 分钟前
为什么选择Redis?解析核心使用场景与性能优化技巧
java·spring boot·redis·intellij-idea
龙大大L1 小时前
第五章:5.1 ESP32物联网应用 - MQTT协议深度教程
java·单片机·struts·apache
极客先躯2 小时前
高级java每日一道面试题-2025年4月01日-微服务篇[Nacos篇]-Nacos集群的数据一致性是如何保证的?
java·开发语言·微服务
麓殇⊙2 小时前
springboot--页面的国际化
java·spring boot·后端
qq_260241232 小时前
网站缓存怎么检查是否生效?
缓存
橙序研工坊2 小时前
JavaWeb-01-前端Web开发(HTML+CSS)
java·前端·css·html·javaweb
码农幻想梦2 小时前
4185 费马小定理求逆元
java·开发语言
汤姆大聪明2 小时前
微服务与Spring Cloud Alibaba简介
java·spring boot·spring·spring cloud·微服务