简体   繁体   English

虚假ConcurrentModificationException

[英]Spurious ConcurrentModificationException

I'm having some issues with a piece of java code which keeps triggering a ConcurrentModificationException. 我在一段Java代码中遇到了一些问题,这些代码不断触发ConcurrentModificationException。 I can't really figure out what is going on, this is a fairly simple static class, not sure why it would be throwing this exception as everything is synchronized. 我真的无法弄清楚到底是怎么回事,这是一个相当简单的静态类,不确定所有同步的原因为什么会抛出此异常。 This piece of code has been heavily used for several years, so it's odd that it would start having issues at this point: 这段代码已经使用了很多年,所以奇怪的是,这时开始出现问题:

java.util.ConcurrentModificationException
        at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:953)
        at java.util.LinkedList$ListItr.next(LinkedList.java:886)
        at DataSubscriptionManager.sendMessages(DataSubscriptionManager.java:18)


private static HashMap<DataClass,LinkedList<DataSubscriber>> subscriberMap = new HashMap();

 public static void sendMessages(LinkedList messages, DataClass dataClass) {
  synchronized (subscriberMap) {
   LinkedList<DataSubscriber> subscribers = subscriberMap.get(dataClass);
   if (subscribers != null) {
    for (DataSubscriber sub: subscribers) { *** EXCEPTION HAPPENS HERE***
     if (sub != null) {
      sub.sendMessages(messages);
     }
    }
   }
  }
 }


 public static void addDataSubscriber(DataSubscriber sub, DataClass dataClass) {
  synchronized (subscriberMap) {
   LinkedList<DataSubscriber> subscribers = subscriberMap.get(dataClass);
   if (subscribers == null) {
    subscribers = new LinkedList();
    subscriberMap.put(dataClass,subscribers);
   }
   while (subscribers.remove(sub)) {}
   subscribers.add(sub);
  }
 }

 public static void removeDataSubscriber(DataSubscriber sub, DataClass dataClass) {
  synchronized (subscriberMap) {
   LinkedList<DataSubscriber> subscribers = subscriberMap.get(dataClass);

   subscribers.remove(sub);
  }
 }

What's happening is that your collection is being modified while you are iterating over it. 发生的情况是,您在遍历集合时对其进行了修改。

It's could be another thread, or it's possible one of your subscribers is either unsubscribing, or subscribing to a different dataClass in response to the message it receives. 这可能是另一个线程,或者您的一个订阅者可能正在取消订阅,或者正在订阅另一个dataClass以响应其收到的消息。

您可以尝试使用Collections.synchronizedList(subscribers),这可能有助于避免此问题。

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

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