有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

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

但有多个线程正在读取此地图。如果只有一个writer但有多个reader,我是否需要一个ConcurrentHashMap


共 (2) 个答案

  1. # 1 楼答案

    是的,如果您在多线程环境中工作,那么您必须考虑同步,否则将传递意外数据。p>

  2. # 2 楼答案

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

    HashMapJavadoc开始:

    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.