高效缓存设计的哲学

文章目录

引言

基于缓存存储运算结果

利用缓存避免非必要的计算,提升结果获取速度,但还是存在问题,每个线程都需要等待锁才能看结果和运算:

java 复制代码
 public final Map<Integer, Integer> cache = new HashMap<>();


    public synchronized int compute(int arg) {

        if (cache.containsKey(arg)) {//若存在直接返回结果
            return cache.get(arg);
        } else {//若不存在则计算并返回
            int result = doCompute(arg);
            cache.put(arg, result);
            return result;
        }
    }

    private int doCompute(int key) {
        ThreadUtil.sleep(500);
        return key << 1;
    }

锁分段散列减小锁粒度

利用分段锁分散压力,但是运算耗时可能导致重复计算和put操作:

java 复制代码
public final Map<Integer, Integer> cache = new ConcurrentHashMap<>();


    public int compute(int arg) {
        Integer res = cache.get(arg);
        if (res == null) {
            int result = doCpmpute(arg);
            cache.put(arg, result);
        }
        return res;
    }

    private int doCpmpute(int arg) {
        ThreadUtil.sleep(3000);
        return arg << 1;
    }

异步化提升处理效率

使用future避免计算的阻塞,当然因为判空和创建任务非原子操作,很可能还是出现重复计算的情况:

java 复制代码
public final Map<Integer, FutureTask<Integer>> cache = new ConcurrentHashMap<>();


    public int compute(int key) throws ExecutionException, InterruptedException {
        FutureTask<Integer> f = cache.get(key);
        if (f == null) {
            FutureTask<Integer> futureTask = new FutureTask<>(() -> doCompute(key));
            //缓存保证下一个线程看到时直接取出使用
            cache.put(key, futureTask);
            futureTask.run();
            f=futureTask ;
        }
        return f.get();
    }

    private int doCompute(int arg) {
        ThreadUtil.sleep(3000);
        return arg << 1;
    }

原子化避免重复运算

原子操作避免重复计算,并发运算一个数字时都采用同一个任务的结果

java 复制代码
public int compute(int key) throws ExecutionException, InterruptedException {
        FutureTask<Integer> f = cache.get(key);
        if (f == null) {
            FutureTask<Integer> futureTask = new FutureTask<>(() -> doCompute(key));
            //原子操作添加,若返回空说明第一次添加,则让这个任务启动,其他线程直接基于缓存中的任务获取结果
            f = cache.putIfAbsent(key, futureTask);
            if (f == null) {
                f = futureTask;
                f.run();
            }
            futureTask.run();
            f = futureTask;
        }
        return f.get();
    }

小结

参考

相关推荐
在未来等你3 小时前
AI Agent设计模式 Day 2:Plan-and-Execute模式:先规划后执行的智能策略
设计模式·llm·react·ai agent·plan-and-execute
今天没有盐7 小时前
Pandas缺失值处理完全指南:从基础操作到高级技巧
python·pycharm·编程语言
在未来等你9 小时前
AI Agent设计模式 Day 3:Self-Ask模式:自我提问驱动的推理链
设计模式·llm·react·ai agent·plan-and-execute
xiaodaidai丶16 小时前
设计模式之策略模式
设计模式·策略模式
_院长大人_17 小时前
设计模式-工厂模式
java·开发语言·设计模式
今天没有盐1 天前
Pandas完全指南:从Series到DataFrame,掌握数据分析核心技能
python·pycharm·编程语言
王道长服务器 | 亚马逊云1 天前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
在未来等你1 天前
AI Agent设计模式 Day 1:ReAct模式:推理与行动的完美结合
设计模式·llm·react·ai agent·plan-and-execute
乐悠小码2 天前
Java设计模式精讲---03建造者模式
java·设计模式·建造者模式
_院长大人_2 天前
设计模式-代理模式
设计模式·代理模式