简体   繁体   English

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

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

Our legacy multi-threaded application has a lots of usage of Hashtable. 我们的旧式多线程应用程序具有大量的Hashtable用法。 Is it safe to replace the Hashtable instances with ConcurrentHashmap instances for performance gain? 用ConcurrentHashmap实例替换Hashtable实例是否安全以提高性能? Will there be any side effect? 会不会有副作用?

Is it safe to replace the Hashtable instances with ConcurrentHashmap instances for performance gain? 用ConcurrentHashmap实例替换Hashtable实例是否安全以提高性能?

In most cases it should be safe and yield better performance. 在大多数情况下,它应该安全并产生更好的性能。 The effort on changing depends on whether you used the Map interface or Hashtable directly. 更改的工作量取决于您是直接使用Map界面还是Hashtable

Will there be any side effect? 会不会有副作用?

There might be side effects if your application expects to immediately be able to access elements that were put into the map by another thread. 如果您的应用程序希望立即能够访问另一个线程放入映射中的元素,则可能会有副作用。

From the JavaDoc on ConcurrentHashMap: 从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 : to clarify on "immediately" consider thread 1 adds element A to the map and while that write is executed thread 2 tries to whether A exists in the map. 编辑 :为了“立即”澄清,考虑线程1将元素A添加到映射中,并且在执行写入操作时,线程2尝试确定映射中是否存在A。 With Hashtable thread 2 would be blocked until after the write so the check would return true but when using ConcurrentHashMap it would return false since thread 2 would not be blocked and the write operation is not yet completed (thus thread 2 would see an outdated version of the bucket). 使用Hashtable线程2将被阻塞,直到写入后才执行,因此检查将返回true,但使用ConcurrentHashMap ,它将返回false,因为线程2将不会被阻塞并且写入操作尚未完成(因此线程2将看到过时的版本)。桶)。

Depending on the size of your Hashtable objects you might get some performance gains by switching to ConcurrentHashmap . 根据Hashtable对象的大小,切换到ConcurrentHashmap可能会提高性能。

ConcurrentHashmap is broken into segments which allow for the table to be only partially locked. ConcurrentHashmap分为多个段,这些段仅允许部分锁定表。 This means that you can get more accesses per second than a Hashtable , which requires that you lock the entire table. 这意味着您可以获得比Hashtable每秒更多的访问Hashtable ,而Hashtable要求您锁定整个表。

The tables themselves are both thread safe and both implement the Map interface, so replacement should be relatively easy. 这些表本身都是线程安全的,并且都实现了Map接口,因此替换应该相对容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM