java并发集合类 设计思想

为什么并发集合类不支持null

按照设计者Doug Lea自己的说法是:

The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated. The main one is that if map.get(key) returns null, you can't detect whether the key explicitly maps to null vs the key isn't mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

在ConcurrentMap中不允许null的原因是在非并发map允许的歧义性在并发环境下是不允许的。以null值来说,在并发环境下,无法分辨map.get(key)返回null是键不存在,还是值为null。在非并发环境下,可以使用map.contains(key)来分辨,但并发环境下两次调用期间map可能发生了改变。

我也赞同Doug Lea的说法:

I personally think that allowing nulls in Maps (also Sets) is an open invitation for programs to contain errors that remain undetected until they break at just the wrong time.

在集合中允许null(键/值),本质是对程序逃避检查错误直到错误爆发的一种鼓励。

posted @ 2018-08-02 18:23  redreampt  阅读(284)  评论(0编辑  收藏  举报