缓存,futureTask,并发

/**
     * 并发性太差,主要体现在计算不同值,计算相同值效率高
     */
    @Test
    public synchronized void cache1() {
        Map<String, String> cache = new HashMap<>();
        String result = cache.get(arg);
        if (result == null) {
            result = compute(arg);
            cache.put(arg, result);
            System.out.println(result);
        }
    }

    /**
     * 计算相同值时存在重复计算,不同值时效率高
     */
    @Test
    public void cache2() {
        Map<String, String> cache = new ConcurrentHashMap<>();
        String result = cache.get(arg);
        if (result == null) {
            result = compute(arg);
            cache.put(arg, result);
            System.out.println(result);
        }
    }

    //对于同一个值,因为get的value是futureTask,所以速度快很多,出现重复计算同一个值
    //的几率小很多
    @Test
    public void cache3() throws Exception {

        Map<String, FutureTask<String>> cache = new ConcurrentHashMap<>();
        if (cache.get(arg) == null) {
            FutureTask<String> futureTask = new FutureTask<>(() -> compute(arg));
            cache.put(arg, futureTask);
            String result = futureTask.get();
            System.out.println("result = " + result);
        } else {
            System.out.println(cache.get(arg).get());
        }
    }

    /**
     * 相同值时,利用原子的putIfAbsent判断是否有值,避免了重复计算
     * @throws Exception
     */
    @Test
    public void cache4() throws Exception{
        Map<String, FutureTask<String>> cache = new ConcurrentHashMap<>();
        if(cache.get(arg)==null){
            FutureTask<String> futureTask = new FutureTask<>(() -> compute(arg));
            FutureTask<String> f = cache.putIfAbsent(arg, futureTask);
            if(f==null){
                String result = futureTask.get();
                System.out.println("result = " + result);
            }else{
                cache.get(arg).get();
            }
        }else{
            cache.get(arg).get();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值