[关闭]
@lyxiang 2019-07-08T14:33:20.000000Z 字数 1512 阅读 1786

ConcurrentHashMap的key,value均不能为空


一次偶然的意外

在一次开发过程中,出现了下面的bug。

  1. Map<String, String> hashMap = new HashMap<>();
  2. System.out.println(map.keySet().contains(null)); //output:false
  3. ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<>();
  4. System.out.println(concurrentHashMap.keySet().contains(null) // throw NullPointerException

问题的原因

  1. public boolean contains(Object o) {
  2. return map.containsKey(o);
  3. }
  4. public boolean containsKey(Object key) {
  5. return getNode(hash(key), key) != null;
  6. }
  7. static final int hash(Object key) {
  8. int h;
  9. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  10. }
  1. public boolean contains(Object o) {
  2. return map.containsKey(o);
  3. }
  4. public boolean containsKey(Object key) {
  5. return get(key) != null;
  6. }
  7. public V get(Object key) {
  8. Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
  9. int h = spread(key.hashCode()); //存在NPE风险
  10. if ((tab = table) != null && (n = tab.length) > 0 &&
  11. (e = tabAt(tab, (n - 1) & h)) != null) {
  12. if ((eh = e.hash) == h) {
  13. if ((ek = e.key) == key || (ek != null && key.equals(ek)))
  14. return e.val;
  15. }
  16. else if (eh < 0)
  17. return (p = e.find(h, key)) != null ? p.val : null;
  18. while ((e = e.next) != null) {
  19. if (e.hash == h &&
  20. ((ek = e.key) == key || (ek != null && key.equals(ek))))
  21. return e.val;
  22. }
  23. }
  24. return null;
  25. }

问题跟踪

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注