我有一个映射,这是由几个线程并发修改。

在Java API中似乎有三种不同的同步Map实现:

哈希表 collections . synchronizedmap(地图) ConcurrentHashMap

根据我的理解,Hashtable是一个旧的实现(扩展了过时的Dictionary类),后来为了适应Map接口而进行了调整。虽然它是同步的,但它似乎有严重的可伸缩性问题,不推荐用于新项目。

那另外两个呢?Collections.synchronizedMap(Map)和ConcurrentHashMaps返回的Map之间有什么区别?哪一种适合哪种情况?


当前回答

哈希表和ConcurrentHashMap不允许空键或空值。 synchronizedmap (Map)同步所有操作(get、put、size等)。 ConcurrentHashMap支持检索的完全并发性,以及可调的更新预期并发性。

像往常一样,这涉及到并发性、开销和速度的权衡。您确实需要考虑应用程序的详细并发需求来做出决定,然后测试您的代码,看看它是否足够好。

其他回答

ConcurrentHashMap针对并发访问进行了优化。

访问不锁定整个映射,而是使用更细粒度的策略,这提高了可伸缩性。还有专门针对并发访问的功能增强,例如并发迭代器。

ConcurrentHashMap

ConcurrentHashMap for performance-critical applications where there are far more write operations than there are read operations. It is thread safe without synchronizing the whole map. Reads can happen very fast while write is done with a lock. There is no locking at the object level. The locking is at a much finer granularity at a hashmap bucket level. ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it. ConcurrentHashMap uses multitude of locks. read operations are non-blocking, whereas write operations take a lock on a particular segment or bucket.

SynchronizedHashMap

对象级同步。 每个读/写操作都需要获得锁。 锁定整个集合是一种性能开销。 这实际上只允许一个线程访问整个映射,并阻塞了所有其他线程。 这可能会引起争论。 SynchronizedHashMap返回迭代器,它在并发修改时快速失败。

Collection.synchronizedMap ()

Collections实用程序类提供了操作集合并返回包装集合的多态算法。它的synchronizedMap()方法提供了线程安全的功能。 当数据一致性至关重要时,我们需要使用Collections.synchronizedMap()。

我们可以通过使用ConcurrentHashMap和synchronisedHashmap和Hashtable来实现线程安全。但如果你看看他们的架构,就会发现有很多不同。

synchronisedHashmap和Hashtable

两者都将在对象级别上维护锁。所以如果你想执行任何操作,比如put/get,那么你必须先获得锁。同时,其他线程不允许执行任何操作。所以在同一时间,只有一个线程可以操作这个。所以这里的等待时间会增加。我们可以说,与ConcurrentHashMap相比,性能相对较低。

ConcurrentHashMap

It will maintain the lock at segment level. It has 16 segments and maintains the concurrency level as 16 by default. So at a time, 16 threads can be able to operate on ConcurrentHashMap. Moreover, read operation doesn't require a lock. So any number of threads can perform a get operation on it. If thread1 wants to perform put operation in segment 2 and thread2 wants to perform put operation on segment 4 then it is allowed here. Means, 16 threads can perform update(put/delete) operation on ConcurrentHashMap at a time. So that the waiting time will be less here. Hence the performance is relatively better than synchronisedHashmap and Hashtable.

在ConcurrentHashMap中,锁应用于一个段而不是整个Map。 每个段管理自己的内部哈希表。该锁仅应用于更新操作。synchronizedmap (Map)同步整个映射。

哈希表和ConcurrentHashMap不允许空键或空值。 synchronizedmap (Map)同步所有操作(get、put、size等)。 ConcurrentHashMap支持检索的完全并发性,以及可调的更新预期并发性。

像往常一样,这涉及到并发性、开销和速度的权衡。您确实需要考虑应用程序的详细并发需求来做出决定,然后测试您的代码,看看它是否足够好。