zoukankan      html  css  js  c++  java
  • ConcurrentHashMap并不是完全的线程安全

    ConcurrentHashMap通过分段锁的方式实现了高效率的线程安全,但是它能否在所有高并发场景中都能保证线程安全呢?

    public class TestClass {
        private ConcurrentHashMap<String, Integer> map=new ConcurrentHashMap<String, Integer>();
        
        public synchronized void add(String key){
            Integer value=map.get(key); 
            if(value==null)
                map.put(key, 1);
            else
                map.put(key, value+1);
    
            System.out.println(map.get(key));
        }
        public static void main(String[] args) {
             final TestClass t=new TestClass();
             for (int i = 0; i < 10000; i++) {
                new Thread(new Runnable() {
                @Override
                public void run() {
                    t.add("key");
                }
            }).start();
            }
        }
    }

    如果将add方法前的synchronized去掉后输出结果为:9305,并不是想象中的10000。

    如果只是调用put或者get方法,ConcurrentHashMap是线程安全的,但是如果调用了get后在调用map.put(key, value+1)之前有另外的线程去调用了put,然后你再去执行put,就有可能将结果覆盖掉,但这个其实也不能算ConcurrentHashMap线程不安全,ConcurrentHashMap内部操作是线程安全的,但是外部操作还是要靠自己来保证同步,即使在线程安全的情况下,也是可能违反原子操作规则。。。

  • 相关阅读:
    mybatis plus 执行sql
    springboot 打印 mybatisplus 的sql
    easyexcel 简单使用
    springboot ehcache
    easyexcel 时间转换
    springboot stopwatch
    c# 开机自动启动
    sqlHelper
    DirectX录音
    c# 发邮件
  • 原文地址:https://www.cnblogs.com/akaneblog/p/6804470.html
Copyright © 2011-2022 走看看