简体   繁体   English

同时迭代HashMap对象是否是线程安全的?

[英]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) 但是如果任何线程添加或删除一个项,这将在任何其他只是迭代HashMap的线程中抛出异常(实际上是任何集合)

If you are going to iterate of a Map repeatedly you may find it marginally faster to iterate over an array copy. 如果要重复迭代Map,可能会发现迭代数组副本的速度要快一些。

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. 顺便说一句:你可以让一个线程修改/替换propertyEntries,同时在这个模式的许多线程中进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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