记一次多线程并发问题分析

查看一个新来同事的代码(比我高两个级别,心态略崩),发现一个典型的多线程并发问题,在此记录一下。

需求:有个数据需要从其他服务获取,采用rpc的方式获取到后在本地缓存10秒钟
经简化形成后如下代码


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Scratch {

    /**
     * 超时时间 10秒
     */
    public static final long REPLACE_URL_TIME_OUT = 10000l;
    /**
     * 超时时间 9秒
     */
    public static final long REPLACE_URL_TIME_OUT_E = 9000l;

    /**
     * 替换本地缓存
     */
    private static String replaceLink;
    /**
     * 上次获取替换时间
     */
    private static long replaceLinkTime = 0l;
    /**
     * 是否正在查询接口
     */
    private static volatile boolean isQuery = false;

    private  String getUsableUrl() {
        Long nowTime = System.currentTimeMillis();
        //是否超时 true 是 false 否
        boolean isTimeOut = nowTime - replaceLinkTime > REPLACE_URL_TIME_OUT;
        //数据存在且未超时
        if (replaceLink!=null && !isTimeOut) {
            return replaceLink;
        }
        //如果正在进行查询返回缓存数据
        if (isQuery) {
            return replaceLink;
        }
        try {
            //标记已经有线程开始查询
            isQuery = true;
            //本地缓存中如果没有有效的,就去Dubbo服务查询
            String usableUrl = "从duubo获取到的";
            if (usableUrl==null) {
                System.out.println("获取失败");
                //1秒内的请求不再调用接口查询
                replaceLinkTime = nowTime - REPLACE_URL_TIME_OUT_E;
                return replaceLink;
            }
            System.out.println("当前时间:{" + nowTime + "},上次访问时间:{" + replaceLinkTime + "},是否超时:{}" + isTimeOut);
            //缓存数据及时间
            replaceLink = usableUrl;
            replaceLinkTime = nowTime;
        } catch (Exception e) {
            //1秒内的请求不再调用接口查询
            replaceLinkTime = nowTime - REPLACE_URL_TIME_OUT_E;
            System.out.println("获取异常" );
        } finally {
            //完成查询
            isQuery = false;
        }
        return replaceLink;
    }

    public static void main(String[] args) {
        Scratch aspect = new Scratch();
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 20; i++) {
            threadPool.execute(() -> System.out.println(Thread.currentThread().getName()+aspect.getUsableUrl()));
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 20; i++) {
            threadPool.execute(() -> System.out.println(Thread.currentThread().getName() + aspect.getUsableUrl()));
        }

    }
}

代码分析:

  1. 高并发下问题一

首先replaceLink为null多个线程访问时,其中有一个线程将isQuery设置为true,其他线程判断isQuery这个字段时已经为true而此时replaceLink还是为null,该方法将直接返回null。

				//如果正在进行查询返回缓存数据
        if (isQuery) {
            return replaceLink;
        }
        try {
            //标记已经有线程开始查询
            isQuery = true;
          。。。。。。
  1. 高并发下问题二

已经过了过期时间。多个线程走到如下代码处都判断isQuery为false从而都去调用dubbo接口获取最新数据。造成缓存击穿问题(大量请求不走缓存)

				//如果正在进行查询返回缓存数据
        if (isQuery) {
            return replaceLink;
        }
  1. Volatitle关键字理解不足

    Volatitle关键字的作用是保证内存可见性和禁止指令重排序。深入理解虚拟机第三版12.3.3 606页给出了其中的使用场景。
    在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值