1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17 package com.android.systemui.util.leak; 18 19 import android.os.SystemClock; 20 21 import java.lang.ref.Reference; 22 import java.lang.ref.ReferenceQueue; 23 import java.lang.ref.WeakReference; 24 25 /** 26 * Utilities for writing tests that manipulate weak or other references. 27 */ 28 public class ReferenceTestUtils { 29 30 /** Returns a runnable that blocks until {@code o} has been collected. */ createCollectionWaiter(Object o)31 public static CollectionWaiter createCollectionWaiter(Object o) { 32 ReferenceQueue<Object> q = new ReferenceQueue<>(); 33 Reference<?> ref = new WeakReference<>(o, q); 34 o = null; // Ensure this variable can't be referenced from the lambda. 35 36 return () -> { 37 Runtime.getRuntime().gc(); 38 while (true) { 39 try { 40 if (q.remove(5_000) == ref) { 41 return; 42 } else { 43 throw new RuntimeException("timeout while waiting for object collection"); 44 } 45 } catch (InterruptedException e) { 46 Thread.currentThread().interrupt(); 47 } 48 } 49 }; 50 } 51 waitForCondition(Condition p)52 public static void waitForCondition(Condition p) { 53 long deadline = SystemClock.uptimeMillis() + 5_000; 54 while (!p.apply()) { 55 if (SystemClock.uptimeMillis() > deadline) { 56 throw new RuntimeException("timeout while waiting for condition"); 57 } 58 SystemClock.sleep(100); 59 } 60 } 61 62 public interface Condition { apply()63 boolean apply(); 64 } 65 66 public interface CollectionWaiter { waitForCollection()67 void waitForCollection(); 68 } 69 } 70