• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 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.os;
18 
19 import android.annotation.NonNull;
20 import android.os.Handler;
21 import android.os.HandlerExecutor;
22 import android.os.HandlerThread;
23 import android.os.Looper;
24 import android.os.Trace;
25 
26 import java.util.concurrent.Executor;
27 
28 /**
29  * Shared singleton background thread for each process.
30  */
31 @android.ravenwood.annotation.RavenwoodKeepWholeClass
32 public final class BackgroundThread extends HandlerThread {
33     private static final long SLOW_DISPATCH_THRESHOLD_MS = 10_000;
34     private static final long SLOW_DELIVERY_THRESHOLD_MS = 30_000;
35     private static BackgroundThread sInstance;
36     private static Handler sHandler;
37     private static HandlerExecutor sHandlerExecutor;
38 
BackgroundThread()39     private BackgroundThread() {
40         super("android.bg", android.os.Process.THREAD_PRIORITY_BACKGROUND);
41     }
42 
ensureThreadLocked()43     private static void ensureThreadLocked() {
44         if (sInstance == null) {
45             sInstance = new BackgroundThread();
46             sInstance.start();
47             final Looper looper = sInstance.getLooper();
48             looper.setTraceTag(Trace.TRACE_TAG_SYSTEM_SERVER);
49             looper.setSlowLogThresholdMs(
50                     SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
51             sHandler = new Handler(sInstance.getLooper(), /*callback=*/ null, /* async=*/ false,
52                     /* shared=*/ true);
53             sHandlerExecutor = new HandlerExecutor(sHandler);
54         }
55     }
56 
57     @NonNull
get()58     public static BackgroundThread get() {
59         synchronized (BackgroundThread.class) {
60             ensureThreadLocked();
61             return sInstance;
62         }
63     }
64 
65     @NonNull
getHandler()66     public static Handler getHandler() {
67         synchronized (BackgroundThread.class) {
68             ensureThreadLocked();
69             return sHandler;
70         }
71     }
72 
73     @NonNull
getExecutor()74     public static Executor getExecutor() {
75         synchronized (BackgroundThread.class) {
76             ensureThreadLocked();
77             return sHandlerExecutor;
78         }
79     }
80 }
81