简体   繁体   English

无法同步(java.util.ConcurrentModificationException)

[英]Can't synchronize (java.util.ConcurrentModificationException)

I have the following Java code: 我有以下Java代码:

private Object guiUpdateLock = new Object();

public void updateLinkBar(SortedSet<Arbitrage> arbitrages) {
    synchronized (guiUpdateLock) {
        System.out.println("start");
        for (Arbitrage arbitrage : arbitrages) {
          //do some GUI stuff
        }
        System.out.println("end");
    }
}

updateLinkBar() is called from many threads, and occasionally I get java.util.ConcurrentModificationException in "for" cycle. 从许多线程调用updateLinkBar(),有时我在“ for”循环中得到java.util.ConcurrentModificationException。 But I can't understand why since I'm making a lock on object which obviously doesn't work because I can see two "start" in a row in the output. 但是我不明白为什么,因为我要锁定一个显然不起作用的对象,因为我可以在输出中连续看到两个“开始”。

Thank you in advance. 先感谢您。

Locks must protect objects and not segments of code. 锁必须保护对象而不是代码段。

In your case you accept an arbitrary collection, acquire your private lock, and operate on the collection. 在您的情况下,您可以接受任意集合,获取私有锁,然后对该集合进行操作。 Meanwhile the rest of your code may, in other threads, do whatever it wants with the collection and it doesn't have to contend for your private lock to do it. 同时,您的其余代码可以在其他线程中对集合执行任何操作,而不必争夺您的私有锁来执行此操作。

You must significantly redesign your code such that all access to the collection in question is covered by the same lock. 您必须对代码进行重大的重新设计,以使对相关集合的所有访问都被同一锁覆盖。

Without your complete code I have to resort to guessing, but the most likely case is that the two threads are using different guiUpdateLog -Objects to synchronize on. 没有完整的代码,我不得不猜测,但是最有可能的情况是,两个线程正在使用不同的guiUpdateLog -Objects进行同步。 My further guessing would be that they are using different instances of the class that contains the guiUpdateLock - and since it is not static there will be different Object -instances as well. 我的猜测进一步将他们正在使用包含类的不同实例guiUpdateLock -并且因为它是不是静态会有不同的Object -instances为好。

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

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