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(键/值),本质是对程序逃避检查错误直到错误爆发的一种鼓励。

转载于:https://www.cnblogs.com/redreampt/p/9408964.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值