当前位置: 首页 > news >正文

多线程下使用缓存+锁Lock, 出现“锁失效” + “缓存未命中竞争”的缓存击穿情况,双重检查缓存解决问题

多线程情况下,想通过缓存+同步锁的机制去避免多次重复处理逻辑,尤其是I/0操作,但是在实际的操作过程中发现多次访问的日志

2025-06-05 17:30:27.683 [ForkJoinPool.commonPool-worker-3] INFO Rule - [vagueNameMilvusReacll,285] - embedding time-consuming:503 
2025-06-05 17:30:29.693 [ForkJoinPool.commonPool-worker-3] INFO Rule - [vagueNameMilvusReacll,314] - milvus time-consuming:2010 
2025-06-05 17:30:29.701 [ForkJoinPool.commonPool-worker-3] INFO Rule - [vagueNameMilvusReacll,358] - vagueName time-consuming:2534 2025-06-05 17:30:30.135 [ForkJoinPool.commonPool-worker-11] INFO Rule - [vagueNameMilvusReacll,285] - embedding time-consuming:434 
2025-06-05 17:30:30.363 [ForkJoinPool.commonPool-worker-11] INFO Rule - [vagueNameMilvusReacll,314] - milvus time-consuming:228 
2025-06-05 17:30:30.369 [ForkJoinPool.commonPool-worker-11] INFO Rule - [vagueNameMilvusReacll,358] - vagueName time-consuming:3202 2025-06-05 17:30:30.750 [ForkJoinPool.commonPool-worker-8] INFO Rule - [vagueNameMilvusReacll,285] - embedding time-consuming:381 
2025-06-05 17:30:31.021 [ForkJoinPool.commonPool-worker-8] INFO Rule - [vagueNameMilvusReacll,314] - milvus time-consuming:270 
2025-06-05 17:30:31.022 [ForkJoinPool.commonPool-worker-8] INFO Rule - [vagueNameMilvusReacll,358] - vagueName time-consuming:3855

代码如下:

public final static Map<String, Lock> keyLockMap = new ConcurrentHashMap<>();Rule cacheRule = (Rule) CacheMap.get(nodeValue);
if (cacheRule != null) {// 返回缓存
}Lock lock = keyLockMap.computeIfAbsent(nodeValue, k -> new ReentrantLock());
lock.lock();
try {}finally {lock.unlock();// 释放锁资源,避免 map 持有无用锁对象太久keyLockMap.remove(nodeValue);
}

实际的问题:
在加锁之前做了第一次缓存检查(没问题),但在加锁之后没有再次检查缓存是否被其他线程填充过!

这就导致多个线程可能都进入了 lock.lock() 后的代码块,并且都执行了实际查询逻辑。

解决方案:双重检查缓存(Double-Checked Caching)

Rule cacheRule = (Rule) CacheMap.get(nodeValue);
if (cacheRule != null) {rule.setKey(cacheRule.getKey());rule.setValue(cacheRule.getValue());return;
}Lock lock = keyLockMap.computeIfAbsent(nodeValue, k -> new ReentrantLock());
lock.lock();
try {// 【关键】第二次检查缓存cacheRule = (Rule) CacheMap.get(nodeValue);if (cacheRule != null) {rule.setKey(cacheRule.getKey());rule.setValue(cacheRule.getValue());return;}// 真正执行 Milvus 请求...// ...// 最后更新缓存CacheMap.put(nodeValue, rule);
} finally {lock.unlock();keyLockMap.remove(nodeValue); // 可选释放锁对象
}

在这里插入图片描述
这个可能出现锁失效的情况
keyLockMap.remove(nodeValue); // 可选释放锁对象
当T1 进入的时候处理完逻辑后,放入缓存,然后删除锁
sleep(xxx)
当T2 进入的时候处理逻辑,发现没有锁,上锁,访问缓存

发现问题了,如果finally 及时删除锁,可能会出现下一个线程重新建立锁对象,然后多了查询缓存的性能消耗。
为了避免这种情况存在

建立LockManager 类管理锁对象,同时对锁进行ttl 保留时间定期任务删除对应的key


import lombok.extern.slf4j.Slf4j;import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;@Slf4j
public class LockManager {private final Map<String, ReentrantLock> lockMap = new ConcurrentHashMap<>();private final Map<String, Long> lastAccessTime = new ConcurrentHashMap<>();private static final long TTL = TimeUnit.MINUTES.toMillis(5); // 锁保留5分钟private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();public LockManager() {startCleanupTask();}// 获取锁,并更新最后访问时间public ReentrantLock getLock(String key) {lastAccessTime.put(key, System.currentTimeMillis());return lockMap.computeIfAbsent(key, k -> new ReentrantLock());}// 清理任务:扫描并移除超时的锁对象private void startCleanupTask() {scheduler.scheduleAtFixedRate(() -> {log.info("------------start check expired lock---------------");long now = System.currentTimeMillis();lastAccessTime.forEach((key, timestamp) -> {if (now - timestamp > TTL) {lockMap.remove(key);lastAccessTime.remove(key);log.info("Removed expired lock for key: {}", key);}});}, 1, 1, TimeUnit.MINUTES); // 每分钟执行一次清理}public void shutdown() {scheduler.shutdownNow();}
}
@Configuration
public class AppConfig {@Bean(destroyMethod = "shutdown")public LockManager lockManager() {return new LockManager();}
}

注入使用

        Lock lock = lockManager.getLock(nodeValue);

在这里插入图片描述

相关文章:

  • 前端基础之《Vue(19)—状态管理》
  • html 滚动条滚动过快会留下边框线
  • pe文件结构(TLS)
  • ABP VNext 与 Neo4j:构建基于图数据库的高效关系查询
  • 第四讲:类和对象(下)
  • 一个WebRTC 分辨率动态爬升问题记录与解决过程
  • 第二十八章 RTC——实时时钟
  • 【Mini-F5265-OB开发板试用测评】显示RTC日历时钟
  • EasyRTC嵌入式音视频通信SDK助力物联网/视频物联网音视频打造全场景应用
  • 简约商务年终工作总结报告PPT模版分享
  • ingress-nginx 开启 Prometheus 监控 + Grafana 查看指标
  • 基于Selenium+Python的web自动化测试框架
  • 【Auto.js例程】华为备忘录导出到其他手机
  • leetcode sql50题
  • grafana-mcp-analyzer:基于 MCP 的轻量 AI 分析监控图表的运维神器!
  • PLSQLDeveloper配置OracleInstantClient连接Oracle数据库
  • F5 – TCP 连接管理:会话、池级和节点级操作
  • vue3:十五、管理员管理-页面搭建
  • MongoDB学习和应用(高效的非关系型数据库)
  • STM32实战: CAN总线数据记录仪设计方案
  • 建设自己的企业网站需要什么资料/网站设计优化
  • 邹城做网站/网站域名查询官网
  • 国家城乡建设网站/宁波seo推广公司排名
  • 天津如何做百度的网站推广/谷歌google搜索引擎入口
  • 九年级上册信息技术做网站/西安百度seo推广电话
  • 建设银行宁德分行网站/搜索引擎排名优化程序