Java ConcurrentHashMap多线程下的正确使用

        HashMap :先说HashMap,HashMap是线程不安全的,在并发环境下,可能会形成环状链表(扩容时可能造成,具体原因自行百度google或查看源码分析),导致get操作时,cpu空转,所以,在并发环境中使用HashMap是非常危险的。

        HashTable : HashTable和HashMap的实现原理几乎一样,差别无非是1.HashTable不允许key和value为null;2.HashTable是线程安全的。但是HashTable线程安全的策略实现代价却太大了,简单粗暴,get/put所有相关操作都是synchronized的,这相当于给整个哈希表加了一把大锁,多线程访问时候,只要有一个线程访问或操作该对象,那其他线程只能阻塞,相当于将所有的操作串行化,在竞争激烈的并发场景中性能就会非常差。

public class Thread1 implements Runnable {

    public static Map<String, Integer> map = new ConcurrentHashMap<>();

    @Override
    public void run() {
        String[] person = new String[]{"张三", "李四", "王五"};
        String current = person[new Random().nextInt(person.length)];

        Integer oldValue, newValue;
        while (true) {
            oldValue = map.get(current);
            if (null == oldValue) {
                newValue = 1;
                if (map.putIfAbsent(current, newValue) == null) {
                    break;
                }
            } else {
                newValue = oldValue + 1;
                if (map.replace(current, oldValue, newValue)) {
                    break;
                }
            }
        }

        System.out.println(current + "当前:" + map.get(current));
    }

}

其中:

V putIfAbsent(K key, V value)

如果key对应的value不存在,则put进去,返回null。否则不put,返回已存在的value。


boolean remove(Object key, Object value)

如果key对应的值是value,则移除K-V,返回true。否则不移除,返回false


boolean replace(K key, V oldValue, V newValue)

如果key对应的当前值是oldValue,则替换为newValue,返回true。否则不替换,返回false


猜你喜欢

转载自blog.csdn.net/guandongsheng110/article/details/80844574