zoukankan      html  css  js  c++  java
  • ConcurrentHashMap 产生NullPointerException

    今天测试在发给我一段报错日志后,根据日志定位到从ConcurrentHashMap 的缓存中get的时候,ConcurrentHashMap的底层抛出了空指针,当时感觉很奇怪为什么在get的时候产生空指针了呢?

    模拟代码:

    ConcurrentHashMap  concurrentHashMap = new ConcurrentHashMap();
    
    ........................................................
    
    concurrentHashMap.get(传入的参数);

    这个地方出现空指针,难道是传入的null 所以出现了空指针了,事实证明确实传入了null,但是我记得hashmap 是可以传入null 的呀? 为什么ConcurrentHashMap 却不行呢?

    相应的去验证了一下,remove  方法发现也不能传入null 进去。

    一、异常分析

    FATAL EXCEPTION: main
    java.lang.NullPointerException
        at java.util.concurrent.ConcurrentHashMap.remove(ConcurrentHashMap.java:921)

    本以为是并发异常,后发现不对,因为ConcurrentHashMap已经使用继承自ReentrantLock的Segment,保证了线程安全,Java如果有这么大的bug肯定早修复了。看了下源码

    发现自己大意了,在获取hashCode时NPE(hashMap不会,因为它会对null key做一次处理)。ConcurrentHashMap不接受null key和null value这个常识一时疏忽了,调用的地方确实有可能传入null。这样在remove前进行null判断即可解决。

    在问题解决后,想到hashMap和linkedhashMap都允许null key和null value,treeMap不允许null key,但允许null value,而ConcurrentHashMap既不允许null key也不允许null value,why?

    二、not allow null key and value
    stackoverflow并结合了源码分析了一下
    (1) treeMap不允许null key是因为compare会导致NPE, 可通过以下代码实现null key支持

    SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>(new Comparator<Integer>() {
     
                                        @Override
                                        public int compare(Integer arg0, Integer arg1) {
                                            if (arg0 == null) {
                                                if (arg1 == null) return 0;
                                                return -1;
                                            }
                                            if (arg1 == null) return 1;
                                            return arg0.compareTo(arg1);
                                        }
                                    });

    (2) ConcurrentHashMap不允许null key和null value,是因为ConcurrentHashMap的锁机制
    对于get(Object key)如果返回null,ConcurrentHashMap没办法判断是key不存在还是value就是null。有人得问了那么hashmap呢, 为什么可以,hashmap我们可以通过下面代码实现判断

  • 相关阅读:
    SpringMVC中静态获取request对象 Spring中获取 HttpServletRequest对象【转载】
    springcloud 的loadbalancer 轮询算法切换方法 2021.4.3
    springboot项目启动增加图标
    rabbitmq 端口作用以及修改方法
    centos8 安装rabbitmq
    springcloud config client Value获取不到信息的问题的处理方法
    springcloud config配置git作为数据源然后启动报错 If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    Sublime Text的列模式如何操作
    centos8 安装redis
    jQuery简单的Ajax调用
  • 原文地址:https://www.cnblogs.com/pony1223/p/9339113.html
Copyright © 2011-2022 走看看