1 // Copyright 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.android_webview; 6 7 import android.annotation.SuppressLint; 8 import android.os.Handler; 9 import android.os.Looper; 10 import android.os.Message; 11 12 import org.chromium.base.Log; 13 import org.chromium.base.ThreadUtils; 14 import org.chromium.base.TraceEvent; 15 16 import java.lang.ref.ReferenceQueue; 17 import java.lang.ref.WeakReference; 18 import java.util.HashSet; 19 import java.util.Set; 20 21 /** 22 * Handles running cleanup tasks when an object becomes eligible for GC. Cleanup tasks 23 * are always executed on the main thread. In general, classes should not have 24 * finalizers and likewise should not use this class for the same reasons. The 25 * exception is where public APIs exist that require native side resources to be 26 * cleaned up in response to java side GC of API objects. (Private/internal 27 * interfaces should always favor explicit resource releases / destroy() 28 * protocol for this rather than depend on GC to trigger native cleanup). 29 * NOTE this uses WeakReference rather than PhantomReference, to avoid delaying the 30 * cleanup processing until after finalizers (if any) have run. In general usage of 31 * this class indicates the client does NOT use finalizers anyway (Good), so this should 32 * not be a visible difference in practice. 33 */ 34 public class CleanupReference extends WeakReference<Object> { 35 private static final String TAG = "CleanupReference"; 36 37 private static final boolean DEBUG = false; // Always check in as false! 38 39 // The VM will enqueue CleanupReference instance onto sGcQueue when it becomes eligible for 40 // garbage collection (i.e. when all references to the underlying object are nullified). 41 // |sReaperThread| processes this queue by forwarding the references on to the UI thread 42 // (via REMOVE_REF message) to perform cleanup. 43 private static ReferenceQueue<Object> sGcQueue = new ReferenceQueue<Object>(); 44 private static Object sCleanupMonitor = new Object(); 45 46 private static final Thread sReaperThread = new Thread(TAG) { 47 @Override 48 @SuppressWarnings("WaitNotInLoop") 49 public void run() { 50 while (true) { 51 try { 52 CleanupReference ref = (CleanupReference) sGcQueue.remove(); 53 if (DEBUG) Log.d(TAG, "removed one ref from GC queue"); 54 synchronized (sCleanupMonitor) { 55 Message.obtain(LazyHolder.sHandler, REMOVE_REF, ref).sendToTarget(); 56 // Give the UI thread chance to run cleanup before looping around and 57 // taking the next item from the queue, to avoid Message bombing it. 58 sCleanupMonitor.wait(500); 59 } 60 } catch (Exception e) { 61 Log.e(TAG, "Queue remove exception:", e); 62 } 63 } 64 } 65 }; 66 67 static { 68 sReaperThread.setDaemon(true); sReaperThread.start()69 sReaperThread.start(); 70 } 71 72 // Message's sent in the |what| field to |sHandler|. 73 74 // Add a new reference to sRefs. |msg.obj| is the CleanupReference to add. 75 private static final int ADD_REF = 1; 76 // Remove reference from sRefs. |msg.obj| is the CleanupReference to remove. 77 private static final int REMOVE_REF = 2; 78 79 /** 80 * This {@link Handler} polls {@link #sRefs}, looking for cleanup tasks that 81 * are ready to run. 82 * This is lazily initialized as ThreadUtils.getUiThreadLooper() may not be 83 * set yet early in startup. 84 */ 85 @SuppressLint("HandlerLeak") 86 private static class LazyHolder { 87 static final Handler sHandler = new Handler(ThreadUtils.getUiThreadLooper()) { 88 @Override 89 public void handleMessage(Message msg) { 90 try { 91 TraceEvent.begin("CleanupReference.LazyHolder.handleMessage"); 92 CleanupReference ref = (CleanupReference) msg.obj; 93 switch (msg.what) { 94 case ADD_REF: 95 sRefs.add(ref); 96 break; 97 case REMOVE_REF: 98 ref.runCleanupTaskInternal(); 99 break; 100 default: 101 Log.e(TAG, "Bad message=%d", msg.what); 102 break; 103 } 104 105 if (DEBUG) Log.d(TAG, "will try and cleanup; max = %d", sRefs.size()); 106 107 synchronized (sCleanupMonitor) { 108 // Always run the cleanup loop here even when adding or removing refs, to 109 // avoid falling behind on rapid garbage allocation inner loops. 110 while ((ref = (CleanupReference) sGcQueue.poll()) != null) { 111 ref.runCleanupTaskInternal(); 112 } 113 sCleanupMonitor.notifyAll(); 114 } 115 } finally { 116 TraceEvent.end("CleanupReference.LazyHolder.handleMessage"); 117 } 118 } 119 }; 120 } 121 122 /** 123 * Keep a strong reference to {@link CleanupReference} so that it will 124 * actually get enqueued. 125 * Only accessed on the UI thread. 126 */ 127 private static Set<CleanupReference> sRefs = new HashSet<CleanupReference>(); 128 129 private Runnable mCleanupTask; 130 131 /** 132 * @param obj the object whose loss of reachability should trigger the 133 * cleanup task. 134 * @param cleanupTask the task to run once obj loses reachability. 135 */ CleanupReference(Object obj, Runnable cleanupTask)136 public CleanupReference(Object obj, Runnable cleanupTask) { 137 super(obj, sGcQueue); 138 if (DEBUG) Log.d(TAG, "+++ CREATED ONE REF"); 139 mCleanupTask = cleanupTask; 140 handleOnUiThread(ADD_REF); 141 } 142 143 /** 144 * Clear the cleanup task {@link Runnable} so that nothing will be done 145 * after garbage collection. 146 */ cleanupNow()147 public void cleanupNow() { 148 handleOnUiThread(REMOVE_REF); 149 } 150 hasCleanedUp()151 public boolean hasCleanedUp() { 152 return mCleanupTask == null; 153 } 154 handleOnUiThread(int what)155 private void handleOnUiThread(int what) { 156 Message msg = Message.obtain(LazyHolder.sHandler, what, this); 157 if (Looper.myLooper() == msg.getTarget().getLooper()) { 158 msg.getTarget().handleMessage(msg); 159 msg.recycle(); 160 } else { 161 msg.sendToTarget(); 162 } 163 } 164 runCleanupTaskInternal()165 private void runCleanupTaskInternal() { 166 if (DEBUG) Log.d(TAG, "runCleanupTaskInternal"); 167 sRefs.remove(this); 168 Runnable cleanupTask = mCleanupTask; 169 mCleanupTask = null; 170 if (cleanupTask != null) { 171 if (DEBUG) Log.i(TAG, "--- CLEANING ONE REF"); 172 cleanupTask.run(); 173 } 174 clear(); 175 } 176 } 177