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 public final class SystemCleaner { 40 SystemCleaner()41 private SystemCleaner() {} 42 43 /** 44 * Return a single Cleaner that's shared across the entire process. Thread-safe. 45 * Unlike normal Cleaners, uncaught exceptions during cleaning will throw an uncaught 46 * exception from the daemon running the cleaning action. This will normally cause the 47 * process to crash, and thus cause the problem to be reported. 48 */ cleaner()49 @NonNull public static Cleaner cleaner() { 50 return CleanerFactory.cleaner(); 51 } 52 } 53 54