From 65292aaa79f94163a73aaa9bd7b3ecbc16b5ec26 Mon Sep 17 00:00:00 2001 From: "Jason A. Donenfeld" Date: Fri, 1 Jun 2018 17:34:59 +0200 Subject: Topic: make reentrant Signed-off-by: Jason A. Donenfeld --- .../java/com/wireguard/android/util/Topic.java | 23 ++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) (limited to 'app/src/main/java') diff --git a/app/src/main/java/com/wireguard/android/util/Topic.java b/app/src/main/java/com/wireguard/android/util/Topic.java index eed13c9e..23f15e6e 100644 --- a/app/src/main/java/com/wireguard/android/util/Topic.java +++ b/app/src/main/java/com/wireguard/android/util/Topic.java @@ -24,7 +24,9 @@ public class Topic { if (subscribers == null) { subscribers = new LinkedList<>(); } - subscribers.add(new WeakReference<>(sub)); + synchronized (subscribers) { + subscribers.add(new WeakReference<>(sub)); + } } public void unsubscribe() { @@ -32,10 +34,12 @@ public class Topic { } public void unsubscribe(Subscriber sub) { - for (Iterator> i = subscribers.iterator(); i.hasNext();) { - WeakReference subscriber = i.next(); - if (subscriber.get() == null || subscriber.get() == sub) { - i.remove(); + synchronized (subscribers) { + for (Iterator> i = subscribers.iterator(); i.hasNext(); ) { + WeakReference subscriber = i.next(); + if (subscriber.get() == null || subscriber.get() == sub) { + i.remove(); + } } } } @@ -58,7 +62,11 @@ public class Topic { state = PUBLISHED; this.results = results; if (subscribers != null) { - for (WeakReference subscriber : subscribers) { + List> subscribersCopy = new LinkedList<>(); + synchronized (subscribers) { + subscribersCopy.addAll(subscribers); + } + for (WeakReference subscriber : subscribersCopy) { if (subscriber.get() != null) subscriber.get().onTopicPublished(this); } @@ -86,12 +94,15 @@ public class Topic { topic.subscribe(this); } } + default void unsubscribeTopics() { for (Topic event : getSubscription()) { event.unsubscribe(this); } } + void onTopicPublished(Topic topic); + Topic[] getSubscription(); } } -- cgit v1.2.3