如果只有一个编写器线程,我们是否需要同步java HashMap获取

我正在维护一个内存中的HashMap,它将testUserIds列表存储到他们的emailId中.

HashMap<Integer, String> testUsers = new HashMap<>()

并且只有一个后台线程读取testUsers列表的添加/删除并在此映射上执行操作.由于只有一个线程写入此映射,因此我不必将其作为同步映射.

但是有多个线程从这张地图中读取.如果只有一个作者但有多个读者,我是否需要ConcurrentHashMap?

解决方法:

是的,您应该使用ConcurrentHashMap(或在外部同步Map).否则,如果编写器线程正在修改Map,而任何其他线程在Map上迭代,则可能会出现ConcurrentModificationException.

来自HashMap的Javadoc:

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

来自ConcurrentModificationException的Javadoc:

java.util.ConcurrentModificationException

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

上一篇:java – 具有null-key功能的线程安全映射


下一篇:java – 在同一个对象上同步两次