Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(390)

Unified Diff: chrome/android/java/src/org/chromium/chrome/browser/TidyHandler.java

Issue 2327833002: Address HandlerLeak lint warnings. (Closed)
Patch Set: Remove suppressions. Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: chrome/android/java/src/org/chromium/chrome/browser/TidyHandler.java
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/TidyHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/TidyHandler.java
new file mode 100644
index 0000000000000000000000000000000000000000..841e3cc4e021a3126dae423f1f25010f118adba0
--- /dev/null
+++ b/chrome/android/java/src/org/chromium/chrome/browser/TidyHandler.java
@@ -0,0 +1,59 @@
+// Copyright 2016 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.chrome.browser;
+
+import android.os.Handler;
+import android.os.Message;
+
+import java.lang.ref.WeakReference;
+
+/**
+ * Abstract Handler subclass that can be used to prevent memory leaks. Handlers may cause leaks if
+ * handling a message is delayed. Messages added to the message queue have a reference to the
+ * Handler and the Handler has a reference to the outer class which prevents the outer class from
+ * being garbage collected. Child classes should be static so that their lifetime isn't tied to the
+ * containing class.
+ * <p>
+ * A sample implementation of a {@link TidyHandler} is shown below:
+ *
+ * <pre>
+ * <code>
+ * {@code public static class ExampleTidyHandler extends TidyHandler<ContainingClass>} {
+ * public ExampleTidyHandler(ContainingClass instance) {
+ * super(instance);
+ * }
+ *
+ * {@literal @}Override
+ * public void handleMessageTidy(Message m, ContainingClass instance) {
+ * instance.doSomeInstanceMethodThatHandlesTheMessage();
+ * }
+ * }
+ * </code>
+ * </pre>
+ *
+ * @param <T> The containing class.
+ */
+public abstract class TidyHandler<T> extends Handler {
+
+ private WeakReference<T> mClassReference;
Ted C 2016/09/13 17:25:54 For the places that use this, do we actually have
+
+ public TidyHandler(T instance) {
+ mClassReference = new WeakReference<T>(instance);
+ }
+
+ @Override
+ public void handleMessage(Message m) {
+ T instance = mClassReference.get();
+ if (instance != null) {
+ handleMessage(m, instance);
+ }
+ }
+
+ protected void baseHandlerHandleMessage(Message m) {
+ super.handleMessage(m);
+ }
+
+ protected abstract void handleMessage(Message m, T instance);
+}

Powered by Google App Engine
This is Rietveld 408576698