From a44aa90fa0a6ae798b483e16a93f2baa9d9843a0 Mon Sep 17 00:00:00 2001 From: civitarese Date: Fri, 4 May 2018 09:36:11 +0200 Subject: [PATCH] Aggiunta sincronizzazione lato server --- src/main/java/chat/ChatServiceImpl.java | 27 +++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/main/java/chat/ChatServiceImpl.java b/src/main/java/chat/ChatServiceImpl.java index 4e1de13..b851ee0 100644 --- a/src/main/java/chat/ChatServiceImpl.java +++ b/src/main/java/chat/ChatServiceImpl.java @@ -15,8 +15,11 @@ public class ChatServiceImpl extends ChatServiceGrpc.ChatServiceImplBase { @Override public StreamObserver chat(final StreamObserver responseObserver){ //the stream used to communicate with a specific client is stored in a hash set (avoiding duplicates) - observers.add(responseObserver); + synchronized (observers) { + observers.add(responseObserver); + + } //it returns the stream that will be used by the clients to send messages. //the client will write on this stream return new StreamObserver() { @@ -30,8 +33,17 @@ public class ChatServiceImpl extends ChatServiceGrpc.ChatServiceImplBase { System.out.println("[MESSAGE RECEIVED] Received a message from "+from+": "+message); + + HashSet copy; + + synchronized (observers) { + + copy = new HashSet<>(observers); + + } + //iterating on all the streams to communicate with all the clients - for(StreamObserver observer: observers){ + for(StreamObserver observer: copy){ //we exclude the one which is sending the message if(!observer.equals(responseObserver)) @@ -45,13 +57,20 @@ public class ChatServiceImpl extends ChatServiceGrpc.ChatServiceImplBase { //if there is an error (client abruptly disconnect) we remove the client. public void onError(Throwable throwable) { - observers.remove(responseObserver); + synchronized (observers) { + + observers.remove(responseObserver); + } } //if the client explicitly terminated, we remove it from the hashset. public void onCompleted() { - observers.remove(responseObserver); + synchronized (observers) { + + observers.remove(responseObserver); + + } } }; } -- 2.18.1