Skip to content

Commit

Permalink
NetworkConnectivity: ensure all accesses to listeners set are synchro…
Browse files Browse the repository at this point in the history
…nised
  • Loading branch information
paddybyers committed Apr 10, 2019
1 parent 6edf717 commit 389cd1d
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions lib/src/main/java/io/ably/lib/transport/NetworkConnectivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down

0 comments on commit 389cd1d

Please sign in to comment.