Fixed ConcurrentModificationException on socket broadcast

This commit is contained in:
Claudio Maggioni 2020-03-25 23:13:17 +01:00
parent 27cb73292c
commit 6c9e2a7d7d

View file

@ -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<Session> 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
*