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