用 ConcurrentHashmap 替换所有出现的 Hashtable 是否安全?

Is it safe to replace all the occurrences of Hashtable with ConcurrentHashmap?

我们遗留的多线程应用程序大量使用了 Hashtable。将 Hashtable 实例替换为 ConcurrentHashmap 实例以提高性能是否安全?会不会有副作用?

根据 Hashtable 对象的大小,切换到 ConcurrentHashmap 可能会获得一些性能提升。

ConcurrentHashmap 被分成多个段,允许 table 仅部分锁定。这意味着您每秒可以获得比 Hashtable 更多的访问权限,这需要您锁定整个 table.

table本身都是线程安全的,并且都实现了Map接口,所以替换应该比较容易。

Is it safe to replace the Hashtable instances with ConcurrentHashmap instances for performance gain?

在大多数情况下,它应该是安全的并且会产生更好的性能。更改的工作量取决于您是使用 Map 界面还是直接使用 Hashtable

Will there be any side effect?

如果您的应用程序希望立即能够访问由另一个线程放入地图中的元素,则可能会产生副作用。

来自 ConcurrentHashMap 上的 JavaDoc:

Retrieval operations (including get) generally do not block, so may overlap 
with update operations (including put and remove). Retrievals reflect the 
results of the most recently completed update operations holding upon their onset.

Edit:澄清 "immediately" 考虑线程 1 将元素 A 添加到映射中,并且在执行写入时线程 2 尝试确定映射中是否存在 A .使用 Hashtable 时,线程 2 将被阻塞直到写入之后,因此检查将 return 为真,但是当使用 ConcurrentHashMap 时,它将 return 为假,因为线程 2 不会被阻塞并且写操作尚未完成(因此线程 2 会看到桶的过时版本)。