1 // Copyright 2019 The Chromium Authors 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.base; 6 7 import java.lang.ref.WeakReference; 8 9 /** Utils for doing garbage collection tests. */ 10 public class GarbageCollectionTestUtils { 11 /** 12 * Relying on just one single GC might make instrumentation tests flaky. 13 * Note that {@link #MAX_GC_ITERATIONS} * {@link #GC_SLEEP_TIME} should not be too large, 14 * since there are tests asserting objects NOT garbage collected. 15 */ 16 private static final int MAX_GC_ITERATIONS = 3; 17 18 private static final long GC_SLEEP_TIME = 10; 19 20 /** 21 * Do garbage collection and see if an object is released. 22 * @param reference A {@link WeakReference} pointing to the object. 23 * @return Whether the object can be garbage-collected. 24 */ canBeGarbageCollected(WeakReference<?> reference)25 public static boolean canBeGarbageCollected(WeakReference<?> reference) { 26 // Robolectric tests, one iteration is enough. 27 final int iterations = MAX_GC_ITERATIONS; 28 final long sleepTime = GC_SLEEP_TIME; 29 Runtime runtime = Runtime.getRuntime(); 30 for (int i = 0; i < iterations; i++) { 31 runtime.runFinalization(); 32 runtime.gc(); 33 if (reference.get() == null) return true; 34 35 // Pause for a while and then go back around the loop to try again. 36 try { 37 Thread.sleep(sleepTime); 38 } catch (InterruptedException e) { 39 // Ignore any interrupts and just try again. 40 } 41 } 42 43 return reference.get() == null; 44 } 45 } 46