ConcurrentHashMap线程安全问题

在使用原子操作进行计数时,我们经常会用到ConcurrentHashMap,虽然ConcurrentHashMap是线程安全的,但是如果你操作的是其本身,并如果使用不当,也会造成很多线程安全问题。
看下面的例子,你觉得会输出多少呢?

public class ConcurrentHashMapTest {

    private static final ConcurrentMap<String, AtomicInteger> CACHE_MAP = new ConcurrentHashMap<>();
    private static final String KEY = "test";

    private static class TestThread implements Runnable{
        @Override
        public void run() {
            if(CACHE_MAP.get(KEY)==null){
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                CACHE_MAP.put(KEY, new AtomicInteger());
            }
            CACHE_MAP.get(KEY).incrementAndGet();
        }
    }

    public static void main(String[] args) {
        new Thread(new TestThread()).start();
        new Thread(new TestThread()).start();
        new Thread(new TestThread()).start();
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("次数:"+CACHE_MAP.get(KEY).get());
    }
}

运行结果:
次数:1

我们有3个线程取访问,照理来说应该是3才对,为什么是1呢?
其实ConcurrentHashMap的put方法跟普通的HashMap没什么区别,如果key相同,依然会覆盖。
要想达到不覆盖,我们可以使用putIfAbsent()方法。
CACHE_MAP.put(KEY, new AtomicInteger());
改为CACHE_MAP.putIfAbsent(KEY, new AtomicInteger());

运行结果如下:

次数:3

一般情况下,建议写一个公共的方法来获取CACHE_MAP中的value。对上面的代码进行优化后如下:

public class ConcurrentHashMapTest {

    private static final ConcurrentMap<String, AtomicInteger> CACHE_MAP = new ConcurrentHashMap<>();
    private static final String KEY = "test";

    private static class TestThread implements Runnable{
        @Override
        public void run() {
            getCacheValue(KEY).incrementAndGet();
        }
    }

    public static AtomicInteger getCacheValue(String key){
        if(CACHE_MAP.get(key)==null){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            CACHE_MAP.putIfAbsent(key, new AtomicInteger());
        }
        return CACHE_MAP.get(key);
    }

    public static void main(String[] args) {
        new Thread(new TestThread()).start();
        new Thread(new TestThread()).start();
        new Thread(new TestThread()).start();
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("次数:"+CACHE_MAP.get(KEY).get());
    }

}

我们的效果达到了,再回头看看putIfAbsent()方法的源码:

    public V put(K key, V value) {
        Segment<K,V> s;
        if (value == null)
            throw new NullPointerException();
        int hash = hash(key);
        int j = (hash >>> segmentShift) & segmentMask;
        if ((s = (Segment<K,V>)UNSAFE.getObject
             (segments, (j << SSHIFT) + SBASE)) == null) 
            s = ensureSegment(j);
        return s.put(key, hash, value, false);
    }

    public V putIfAbsent(K key, V value) {
        Segment<K,V> s;
        if (value == null)
            throw new NullPointerException();
        int hash = hash(key);
        int j = (hash >>> segmentShift) & segmentMask;
        if ((s = (Segment<K,V>)UNSAFE.getObject
             (segments, (j << SSHIFT) + SBASE)) == null)
            s = ensureSegment(j);
        return s.put(key, hash, value, true);
    }

其实put方法与putIfAbsent方法唯一的区别就在于调用s.put(…)方法时,最后一个参数,一个是false,一个是true。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值