1

Consider these two situations:

  1. a map which you are going to populate once at the beginning and then will be accessed from many different threads.
  2. a map which you are going to use as cache that will be accessed from many different threads. you would like to avoid computing the result that will be stored in the map unless it is missing, the get-computation-store block will be synchronized. (and the map will not otherwise be used)

In either of these cases, does ConcurrentHashMap offer you anything additional in terms of thread safety above an ordinary HashMap?

4

2 回答 2

0

线程安全没有区别,没有。对于场景 #2,性能存在差异,时序保证存在微小差异。

您的方案 #2 将没有同步,因此想要使用缓存的线程不必排队等待其他线程完成。但是,为了获得这种好处,您在同步边界处没有硬发生之前的关系,因此两个线程可能会或多或少地同时计算相同的缓存值。只要计算是可重复的,这通常是无害的。

(还有一点区别是 ConcurrentHashMap 不允许null用作键。)

于 2011-12-21T23:05:51.087 回答
0

在第一种情况下,在实践中应该无关紧要,但不能保证写入常规 hashmap 的修改会被其他线程看到。因此,如果一个线程最初创建并填充映射,并且该线程从未与您的其他线程同步,那么这些线程可能永远不会看到设置到映射中的初始值。

上述情况在实践中不太可能发生,并且只需要一个同步事件或在线程之间保证之前发生(例如读取/写入 volatile 变量)以确保理论上的正确性。

在第二种情况下,存在一个问题,因为访问在结构上修改它(添加值)的 HashMap 需要同步。此外,您需要某种类型的同步来建立与其他线程的先发生关系/共享可见性,否则无法保证其他线程会看到您输入的新值。 ConcurrentHashMap 提供这些保证,并且不会中断线程在结构上修改它。

于 2011-12-21T23:05:41.957 回答