• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 android.system;
18 
19 import java.lang.ref.Cleaner;
20 import jdk.internal.ref.CleanerFactory;
21 import libcore.util.NonNull;
22 
23 /**
24  * Java.lang.ref.Cleaner encourages each library to create a Cleaner, with an associated
25  * thread, to process Cleaner Runnables for that library's registered cleaning actions.
26  * This approach isolates cleaning actions from different libraries from each other; a slow cleaning
27  * action in one library will only minimally affect cleaning actions in another.
28  *
29  * However, this comes at the cost of introducing one Cleaner thread per library that uses
30  * Cleaners. This could introduce dozens of additional threads per process, which is often
31  * not an acceptable cost, especially on memory-limited devices.
32  *
33  * SystemCleaner instead provides access to a shared Cleaner, shared across the entire process.
34  * It is greatly preferred when all cleaning actions registered by a client are known to
35  * complete quickly, without explicit I/O, interprocess communication, or network access.
36  * Registering a non-terminating or excessively slow cleaning action with the shared cleaner
37  * may cause the process to perform very badly, hang, or be killed.
38  *
39  * Only for developers of the Android platform itself: As with all Cleaners, use of SystemCleaner
40  * requires an extra thread to be started. This is unsafe for zygote-callable code. Use
41  * NativeAllocationRegistry.
42  */
43 public final class SystemCleaner {
44 
SystemCleaner()45     private SystemCleaner() {}
46 
47     /**
48      * Return a single Cleaner that's shared across the entire process. Thread-safe.
49      */
cleaner()50     @NonNull public static Cleaner cleaner() {
51         // We just abuse CleanerFactory. That has the down side that a runaway Cleaner will cause
52         // issues for system libraries. If this eventually becomes a problem due to widespread use,
53         // we can set up another thread here.
54         // TODO: Add some sort of watchdog for this.
55         return CleanerFactory.cleaner();
56     }
57 }
58 
59