高效缓存设计的哲学

文章目录

引言

基于缓存存储运算结果

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

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();
    }

小结

参考

相关推荐
liulilittle19 小时前
VGW 虚拟路由器ARP剖析
开发语言·c++·编程语言·路由·sd·sdn·vgw
庸了个白19 小时前
一种面向 AIoT 定制化场景的服务架构设计方案
mqtt·设计模式·系统架构·aiot·物联网平台·动态配置·解耦设计
Meteors.1 天前
23种设计模式——访问者模式 (Visitor Pattern)
设计模式·访问者模式
Vallelonga1 天前
Rust 设计模式 Marker Trait + Blanket Implementation
开发语言·设计模式·rust
en-route1 天前
设计模式的底层原理——解耦
设计模式
杯莫停丶1 天前
设计模式之:工厂方法模式
设计模式·工厂方法模式
Deschen1 天前
设计模式-抽象工厂模式
java·设计模式·抽象工厂模式
粘豆煮包1 天前
系统设计 System Design -4-2-系统设计问题-设计类似 TinyURL 的 URL 缩短服务 (改进版)
设计模式·架构
top_designer1 天前
告别“静态”VI手册:InDesign与AE打造可交互的动态品牌规范
设计模式·pdf·交互·vi·工作流·after effects·indesign
非凡的世界1 天前
深入理解 PHP 框架里的设计模式
开发语言·设计模式·php