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