简体   繁体   中英

Is it thread-safe to iterate a HashMap object concurrently?

如果多个线程同时迭代HashMap对象而不修改它 ,那么竞争条件是否存在?

没有竞争,如果你可以保证在迭代时没有其他线程会修改这个HashMap。

Nope, that is perfectly fine. As long as all reads are synchronized with all writes, and all writes are synchronized with each other, there is no harm in concurrent reads; so if there are no writes at all, then all concurrent access is safe.

It will be al right. But if any of the threads add or remove an item, this will throw exception in any other threads that are just iterating HashMap (any collection in fact)

If you are going to iterate of a Map repeatedly you may find it marginally faster to iterate over an array copy.

private final HashMap<String, String> properties = new HashMap<String, String>();
private volatile Map.Entry<String, String>[] propertyEntries = null;

private void updatePropertyEntries() {
    propertyEntries = properties.entrySet().toArray(new Map.Entry[properties.size()]);
}

{
    // no objects created
    for (Map.Entry<String, String> entry : propertyEntries) {

    }
}

BTW: You can have one thread modify/replace the propertyEntries while iterating in many threads with this pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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