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