From 73bb0b10eedea8e06ef1b4ca36c8b009eab460cf Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Fri, 21 Jul 2017 05:18:24 +0800 Subject: [PATCH] Prevent memory leak in CallbackEvent --- .../topjohnwu/magisk/utils/CallbackEvent.java | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/topjohnwu/magisk/utils/CallbackEvent.java b/app/src/main/java/com/topjohnwu/magisk/utils/CallbackEvent.java index 5e4a02c85..be53b089b 100644 --- a/app/src/main/java/com/topjohnwu/magisk/utils/CallbackEvent.java +++ b/app/src/main/java/com/topjohnwu/magisk/utils/CallbackEvent.java @@ -1,19 +1,23 @@ package com.topjohnwu.magisk.utils; +import java.lang.ref.WeakReference; import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; import java.util.Set; public class CallbackEvent { public boolean isTriggered = false; private Result result; - private Set> listeners; + private List>> listeners; public void register(Listener l) { if (listeners == null) { - listeners = new HashSet<>(); + listeners = new LinkedList<>(); } - listeners.add(l); + listeners.add(new WeakReference<>(l)); } public void unRegister() { @@ -21,8 +25,11 @@ public class CallbackEvent { } public void unRegister(Listener l) { - if (listeners != null) { - listeners.remove(l); + for (Iterator>> i = listeners.iterator(); i.hasNext();) { + WeakReference> listener = i.next(); + if (listener.get() == null || listener.get() == l) { + i.remove(); + } } } @@ -34,8 +41,9 @@ public class CallbackEvent { result = r; isTriggered = true; if (listeners != null) { - for (Listener listener : listeners) { - listener.onTrigger(this); + for (WeakReference> listener : listeners) { + if (listener.get() != null) + listener.get().onTrigger(this); } } }