• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.permission.util;
18 
19 import android.annotation.NonNull;
20 import android.os.Handler;
21 import android.os.HandlerExecutor;
22 import android.os.HandlerThread;
23 
24 import com.android.internal.annotations.GuardedBy;
25 
26 import java.util.concurrent.Executor;
27 
28 /**
29  * Shared singleton background thread.
30  */
31 public class BackgroundThread extends HandlerThread {
32     private static final Object sLock = new Object();
33 
34     @GuardedBy("sLock")
35     private static BackgroundThread sInstance;
36     @GuardedBy("sLock")
37     private static Handler sHandler;
38     @GuardedBy("sLock")
39     private static Executor sExecutor;
40 
BackgroundThread()41     private BackgroundThread() {
42         super(BackgroundThread.class.getName());
43     }
44 
45     @GuardedBy("sLock")
ensureInstanceLocked()46     private static void ensureInstanceLocked() {
47         if (sInstance == null) {
48             sInstance = new BackgroundThread();
49             sInstance.start();
50             sHandler = new Handler(sInstance.getLooper());
51             sExecutor = new HandlerExecutor(sHandler);
52         }
53     }
54 
55     /**
56      * Get the singleton instance of thi class.
57      *
58      * @return the singleton instance of thi class
59      */
60     @NonNull
get()61     public static BackgroundThread get() {
62         synchronized (sLock) {
63             ensureInstanceLocked();
64             return sInstance;
65         }
66     }
67 
68     /**
69      * Get the {@link Handler} for this thread.
70      *
71      * @return the {@link Handler} for this thread.
72      */
73     @NonNull
getHandler()74     public static Handler getHandler() {
75         synchronized (sLock) {
76             ensureInstanceLocked();
77             return sHandler;
78         }
79     }
80 
81     /**
82      * Get the {@link Executor} for this thread.
83      *
84      * @return the {@link Executor} for this thread.
85      */
86     @NonNull
getExecutor()87     public static Executor getExecutor() {
88         synchronized (sLock) {
89             ensureInstanceLocked();
90             return sExecutor;
91         }
92     }
93 }
94