首页 > 技术文章 > 线程安全的ConcurrentHashMap ,采用非线程安全方式使用,利用java8 map新方法解决!

irvin-chen 2020-12-26 11:00 原文

一、问题描述:
1、示例代码
 
【错误代码】
public static ThreadSource getThreadSource() {
    String threadName = Thread.currentThread().getName();
    ThreadSource threadSource = map.get(threadName);
    if (threadSource != null) {
        return threadSource;
    }
    threadSource = new ThreadSource();
    map.put(threadName, threadSource);
    return threadSource;
}

说明:Check-Set 的场景是典型的并发场景。并非使用了ConcurrentHashMap这样线程安全的类就一定是线程安全的。还需要正确的使用线程安全类提供的方法。

 

【正确的代码】

public static ThreadSource getThreadSource() {
    String threadName = Thread.currentThread().getName();
//若threadName对应的value为空,会将第二个参数的返回值存入并返回
    return map.computeIfAbsent(threadName, key->new ThreadSource());
}

说明: map是ConcurrentHashMap

computeIfAbsent方法介绍:
参考
https://blog.csdn.net/weixin_38229356/article/details/81129320

同类方法类比:java8新特性之put与compute,computeIfAbsent与putIfAbsent区别
参考:
https://blog.csdn.net/wo415415/article/details/87469226
https://blog.csdn.net/wang_8101/article/details/82191146
 

推荐阅读