xref: /aosp_15_r20/external/leakcanary2/leakcanary-object-watcher/src/main/java/leakcanary/GcTrigger.kt (revision d9e8da70d8c9df9a41d7848ae506fb3115cae6e6)
1 /*
2  * Copyright (C) 2011 Google Inc.
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 package leakcanary
17 
18 /**
19  * [GcTrigger] is used to try triggering garbage collection and enqueuing [KeyedWeakReference] into
20  * the associated [java.lang.ref.ReferenceQueue]. The default implementation [Default] comes from
21  * AOSP.
22  */
interfacenull23 fun interface GcTrigger {
24 
25   /**
26    * Attempts to run garbage collection.
27    */
28   fun runGc()
29 
30   /**
31    * Default implementation of [GcTrigger].
32    */
33   object Default : GcTrigger {
34     override fun runGc() {
35       // Code taken from AOSP FinalizationTest:
36       // https://android.googlesource.com/platform/libcore/+/master/support/src/test/java/libcore/
37       // java/lang/ref/FinalizationTester.java
38       // System.gc() does not garbage collect every time. Runtime.gc() is
39       // more likely to perform a gc.
40       Runtime.getRuntime()
41         .gc()
42       enqueueReferences()
43       System.runFinalization()
44     }
45 
46     private fun enqueueReferences() {
47       // Hack. We don't have a programmatic way to wait for the reference queue daemon to move
48       // references to the appropriate queues.
49       try {
50         Thread.sleep(100)
51       } catch (e: InterruptedException) {
52         throw AssertionError()
53       }
54     }
55   }
56 }
57