From 6c9e2a7d7da42fa366745538514a3c59cf51a814 Mon Sep 17 00:00:00 2001 From: Claudio Maggioni Date: Wed, 25 Mar 2020 23:13:17 +0100 Subject: [PATCH] Fixed ConcurrentModificationException on socket broadcast --- .../smarthut/socket/SensorSocketEndpoint.java | 33 +++++++------------ 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/src/main/java/ch/usi/inf/sa4/sanmarinoes/smarthut/socket/SensorSocketEndpoint.java b/src/main/java/ch/usi/inf/sa4/sanmarinoes/smarthut/socket/SensorSocketEndpoint.java index 2801a74..600bdf4 100644 --- a/src/main/java/ch/usi/inf/sa4/sanmarinoes/smarthut/socket/SensorSocketEndpoint.java +++ b/src/main/java/ch/usi/inf/sa4/sanmarinoes/smarthut/socket/SensorSocketEndpoint.java @@ -1,6 +1,5 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.socket; -import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.didThrow; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonConfig; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User; @@ -8,7 +7,6 @@ import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.gson.Gson; - import java.io.IOException; import java.util.*; import javax.websocket.*; @@ -61,28 +59,19 @@ public class SensorSocketEndpoint extends Endpoint { */ public void broadcast(Object message, User u) { final HashSet sessions = new HashSet<>(authorizedClients.get(u)); - - - - sessions.stream() - .filter( - s -> { - if (s.isOpen()) return true; - sessions.remove(s); - return false; - }) - .forEach(s -> { - synchronized (this){ - try { - s.getBasicRemote().sendText(gson.toJson(message)); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); + for (Session s : sessions) { + try { + if (s.isOpen()) { + s.getBasicRemote().sendText(gson.toJson(message)); + } else { + authorizedClients.remove(u, s); + } + } catch (IOException e) { + e.printStackTrace(); + } + } } - /** * Handles the opening of a socket session with a client *