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》

相关推荐
code_std5 分钟前
保存文件到指定位置,读取/删除指定文件夹中文件
java·spring boot·后端
小许学java12 分钟前
Spring事务和事务传播机制
java·数据库·spring·事务
大学生资源网12 分钟前
基于Javaweb技术的宠物用品商城的设计与实现(源码+文档)
java·mysql·毕业设计·源码·springboot
汤姆yu14 分钟前
基于springboot的热门文创内容推荐分享系统
java·spring boot·后端
星光一影14 分钟前
教育培训机构消课管理系统智慧校园艺术舞蹈美术艺术培训班扣课时教务管理系统
java·spring boot·mysql·vue·mybatis·uniapp
lkbhua莱克瓦2417 分钟前
MySQL介绍
java·开发语言·数据库·笔记·mysql
武昌库里写JAVA20 分钟前
在iview中使用upload组件上传文件之前先做其他的处理
java·vue.js·spring boot·后端·sql
董世昌4124 分钟前
什么是事件冒泡?如何阻止事件冒泡和浏览器默认事件?
java·前端
好度30 分钟前
配置java标准环境?(详细教程)
java·开发语言
teacher伟大光荣且正确35 分钟前
关于Qt QReadWriteLock(读写锁) 以及 QSettings 使用的问题
java·数据库·qt