高效可伸缩的结果缓存

package com.yw.cache;

import javax.annotation.concurrent.GuardedBy;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author x  y
 * @description 高效可伸缩的结果缓存
 * @date 2022-03-16 11:47
 */
public class CacheMain implements Computable<String, BigInteger> {
    
    @Override
    public BigInteger compute(String arg) throws InterruptedException {
        // 在进过长时间计算后
        return new BigInteger(arg);
    }
}

interface Computable<A, V> {
    V compute(A arg) throws InterruptedException;
}

class MemoizerOne<A, V> implements Computable<A, V> {
    @GuardedBy("this")
    private final Map<A, V> cache = new HashMap<>();
    private final Computable<A, V> c;
    private final ReentrantLock lock = new ReentrantLock();

    MemoizerOne(Computable<A, V> computable) {
        this.c = computable;
    }

    @Override
    public V compute(A arg) throws InterruptedException {
        final ReentrantLock l = this.lock;
        l.lock();
        try {
            V result = cache.get(arg);
            if (result == null) {
                result = c.compute(arg);
                cache.put(arg, result);
            }
            return result;
        } finally {
            l.unlock();
        }
    }
}

class MemoizerTwo<A, V> implements Computable<A, V> {
    @GuardedBy("this")
    private final Map<A, V> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> c;

    MemoizerTwo(Computable<A, V> computable) {
        this.c = computable;
    }

    @Override
    public V compute(A arg) throws InterruptedException {
        V result = cache.get(arg);
        if (result == null) {
            result = c.compute(arg);
            cache.put(arg, result);
        }
        return result;
    }
}

class MemoizerThree<A, V> implements Computable<A, V> {
    @GuardedBy("this")
    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> c;

    MemoizerThree(Computable<A, V> computable) {
        this.c = computable;
    }

    /**
     * 检查某个相应的计算已经开始没有,如果还没启动创建一个FutureTask 并注册Map中,然后启动计算;如果启动则等待对应结果即可。
     **/
    @Override
    public V compute(A arg) throws InterruptedException {
        Future<V> result = cache.get(arg);
        if (result == null) {
            Callable<V> callable = new Callable<V>() {
                @Override
                public V call() throws Exception {
                    return c.compute(arg);
                }
            };
            FutureTask task = new FutureTask(callable);
            result = task;
            cache.put(arg, result);
            task.run(); // 在这里调用c.compute(arg)
        }
        try {
            return result.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}

class MemoizerFour<A, V> implements Computable<A, V> {
    @GuardedBy("this")
    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> c;

    MemoizerFour(Computable<A, V> computable) {
        this.c = computable;
    }

    /**
     * 检查某个相应的计算已经开始没有,如果还没启动创建一个FutureTask 并注册Map中,然后启动计算;如果启动则等待对应结果即可。
     * 解决if判断中非原子的先检查在执行操作,所以两个线程仍然有机会同一时间调用compute计算相同值,即两者都没找到期望的值,因此都开始计算。
     **/
    @Override
    public V compute(A arg) throws InterruptedException {
        for (; ; ) { // 为什么不用while(true)因为for会被虚拟机直接优化为死循环,而while(true)还需要运行判断
            Future<V> result = cache.get(arg);
            if (result == null) {
                Callable<V> callable = new Callable<V>() {
                    @Override
                    public V call() throws Exception {
                        return c.compute(arg);
                    }
                };
                FutureTask task = new FutureTask(callable);
                result = cache.putIfAbsent(arg, result);
                if (result == null) {
                    result = task;
                    task.run();// 在这里调用c.compute(arg)}
                }
                try {
                    return result.get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值