From de614c3a892c28165597c137b18c9d45e20ab754 Mon Sep 17 00:00:00 2001 From: Paddy Byers Date: Wed, 10 Apr 2019 17:33:56 +0100 Subject: [PATCH] NetworkConnectivity: ensure all accesses to listeners set are synchronised --- .../lib/transport/NetworkConnectivity.java | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/lib/src/main/java/io/ably/lib/transport/NetworkConnectivity.java b/lib/src/main/java/io/ably/lib/transport/NetworkConnectivity.java index 447281d56..fc40ca03e 100644 --- a/lib/src/main/java/io/ably/lib/transport/NetworkConnectivity.java +++ b/lib/src/main/java/io/ably/lib/transport/NetworkConnectivity.java @@ -13,33 +13,48 @@ public interface NetworkConnectivityListener { } public void addListener(NetworkConnectivityListener listener) { - boolean wasEmpty = listeners.isEmpty(); - listeners.add(listener); + boolean wasEmpty; + synchronized (this) { + wasEmpty = listeners.isEmpty(); + listeners.add(listener); + } if(wasEmpty) { onNonempty(); } } public void removeListener(NetworkConnectivityListener listener) { - listeners.remove(listener); - if(listeners.isEmpty()) { + boolean isEmpty; + synchronized (this) { + listeners.remove(listener); + isEmpty = listeners.isEmpty(); + } + if(isEmpty) { onEmpty(); } } protected void notifyNetworkAvailable() { - for(NetworkConnectivityListener listener: listeners) { + NetworkConnectivityListener[] allListeners; + synchronized(this) { + allListeners = listeners.toArray(new NetworkConnectivityListener[listeners.size()]); + } + for(NetworkConnectivityListener listener: allListeners) { listener.onNetworkAvailable(); } } protected void notifyNetworkUnavailable(ErrorInfo reason) { - for(NetworkConnectivityListener listener: listeners) { + NetworkConnectivityListener[] allListeners; + synchronized(this) { + allListeners = listeners.toArray(new NetworkConnectivityListener[listeners.size()]); + } + for(NetworkConnectivityListener listener: allListeners) { listener.onNetworkUnavailable(reason); } } - protected boolean isEmpty() { + protected synchronized boolean isEmpty() { return listeners.isEmpty(); }