【guava】GuavaCache缓存失效的时候做一些操作 RemovalListener

156 篇文章 452 订阅 ¥39.90 ¥99.00
本文探讨了在Guava Cache中,当缓存项过期时如何利用RemovalListener进行操作。由于GuavaCache不保证过期后立即删除Key,而是依赖于访问时的检查,因此在Key过期后可能不会立即触发回调。文章通过Stack Overflow上的解答解释了这一行为背后的设计考虑,即避免创建维护线程并减少锁的竞争,以确保性能和资源效率。
摘要由CSDN通过智能技术生成

在这里插入图片描述

1.概述

转载:https://blog.csdn.net/chen_kkw/article/details/81144169

缓存策略参考:【Guava】Guava Cache的refresh和expire刷新机制

以为需要我使用guava缓存我的数据库连接,但是因为设置了1分钟失效就关闭,但是关闭的时候,我希望能做些操作,最好是关闭连接,代码如下

private static class MyRemovalListener implements RemovalListener<Integer, Integer> {  
    @Override  
    public void onRemoval(RemovalNotification<Integer, Integer> notification) {  
        doSomething();
    }  
}  

public static Cache<Integer, Integer> cache = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(new MyRemovalListener())
.build();

看上去应该没什么问题,只是测试下来发现回调并不触发,如果手动调用 invalidate(key) 的话,那么就会触发回调,但是这不符合我的需求啊,我是希望 key 在 10 min 过期之后能自己触发回调,而且这 API 既然设计成这样,没道理不能触发,于是开始寻找问题

2.原因

在 Stack Overflow 上找到了原因,原来是 GuavaCache 并不保证在过期时间到了之后立刻删除该 Key,如果你此时去访问了这个 Key,它会检测是不是已经过期,过期就删除它,所以过期时间到了之后你去访问这个 Key 会显示这个 Key 已经被删除,但是如果你不做任何操作,那么在 10 min 到了之后也许这个 Key 还在内存中。GuavaCache 选择这样做的原因也很简单,如下:

The reason for this is as follows: if we wanted to perform Cache maintenance continuously, we would need to create a thread, and its operations would be competing with user operations for shared locks. Additionally, some environments restrict the creation of threads, which would make CacheBuilder unusable in that environment.

这样做既可以保证对 Key 读写的正确性,也可以节省资源,减少竞争。

参考:https://blog.csdn.net/chen_kkw/article/details/81144169

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值