Debian Codegraph @

core/java/com/android/internal/util/GcUtils.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 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.internal.util;
18
19 import android.util.Slog;
20
21 import java.util.concurrent.CountDownLatch;
22 import java.util.concurrent.TimeUnit;
23
24 /**
25 * A helper class to handle gc'ing a process, mainly used for testing.
26 *
27 * @hide
28 */
29 public final class GcUtils {
30 private static final String TAG = GcUtils.class.getSimpleName();
31
32 /**
33 * Runs a GC and attempts to wait for finalization.
34 */
35 public static void runGcAndFinalizersSync() {
36 Runtime.getRuntime().gc();
37 Runtime.getRuntime().runFinalization();
38
39 final CountDownLatch fence = new CountDownLatch(1);
40 createFinalizationObserver(fence);
41 try {
42 do {
43 Runtime.getRuntime().gc();
44 Runtime.getRuntime().runFinalization();
45 } while (!fence.await(100, TimeUnit.MILLISECONDS));
46 } catch (InterruptedException ex) {
47 throw new RuntimeException(ex);
48 }
49 Slog.v(TAG, "Running gc and finalizers");
50 }
51
52 /**
53 * Create the observer in the scope of a method to minimize the chance that
54 * it remains live in a DEX/machine register at the point of the fence guard.
55 * This must be kept to avoid R8 inlining it.
56 */
57 private static void createFinalizationObserver(CountDownLatch fence) {
58 new Object() {
59 @Override
60 protected void finalize() throws Throwable {
61 try {
62 fence.countDown();
63 } finally {
64 super.finalize();
65 }
66 }
67 };
68 }
69
70 // Uninstantiable
71 private GcUtils() {}
72 }