Fix defensive subscriber removal 89/88989/4
authorwsx25289 <10200860@zte.com.cn>
Thu, 9 Apr 2020 07:29:44 +0000 (03:29 -0400)
committerRobert Varga <robert.varga@pantheon.tech>
Tue, 21 Apr 2020 06:43:39 +0000 (08:43 +0200)
Attempting to modify the collection while iterating over it
results in ConcurrentModificationException. Use an explicit
iterator and Iterator.remove() to prevent it.

JIRA: NETCONF-664
Change-Id: I6206dfdd896307f83420cfb3201d1125adbf9a07
Signed-off-by: Wsx25289 <10200860@zte.com.cn>
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
restconf/restconf-nb-rfc8040/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/AbstractCommonSubscriber.java

index c5da51d2092c83dbae09206dcdb4af982b3a309d..2f312aeb5b5db446eea3765254ac01d223a80dbd 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.restconf.nb.rfc8040.streams.listeners;
 import com.google.common.base.Preconditions;
 import java.net.InetSocketAddress;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.Optional;
 import java.util.Set;
 import org.opendaylight.restconf.nb.rfc8040.streams.websockets.WebSocketSessionHandler;
@@ -82,7 +83,9 @@ abstract class AbstractCommonSubscriber extends AbstractQueryParams implements B
      * @param data Data of incoming notifications.
      */
     synchronized void post(final String data) {
-        for (final WebSocketSessionHandler subscriber : subscribers) {
+        final Iterator<WebSocketSessionHandler> iterator = subscribers.iterator();
+        while (iterator.hasNext()) {
+            final WebSocketSessionHandler subscriber = iterator.next();
             final Optional<InetSocketAddress> remoteEndpointAddress = subscriber.getRemoteEndpointAddress();
             if (remoteEndpointAddress.isPresent()) {
                 subscriber.sendDataMessage(data);
@@ -90,9 +93,9 @@ abstract class AbstractCommonSubscriber extends AbstractQueryParams implements B
             } else {
                 // removal is probably not necessary, because it will be removed explicitly soon after invocation of
                 // onWebSocketClosed(..) in handler; but just to be sure ...
-                subscribers.remove(subscriber);
+                iterator.remove();
                 LOG.debug("Subscriber for {} was removed - web-socket session is not open.", this);
             }
         }
     }
-}
\ No newline at end of file
+}