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
17package com.android.internal.os;
18
19import android.os.Handler;
20import android.os.HandlerThread;
21
22/**
23 * Shared singleton background thread for each process.
24 */
25public final class BackgroundThread extends HandlerThread {
26    private static BackgroundThread sInstance;
27    private static Handler sHandler;
28
29    private BackgroundThread() {
30        super("android.bg", android.os.Process.THREAD_PRIORITY_BACKGROUND);
31    }
32
33    private static void ensureThreadLocked() {
34        if (sInstance == null) {
35            sInstance = new BackgroundThread();
36            sInstance.start();
37            sHandler = new Handler(sInstance.getLooper());
38        }
39    }
40
41    public static BackgroundThread get() {
42        synchronized (BackgroundThread.class) {
43            ensureThreadLocked();
44            return sInstance;
45        }
46    }
47
48    public static Handler getHandler() {
49        synchronized (BackgroundThread.class) {
50            ensureThreadLocked();
51            return sHandler;
52        }
53    }
54}
55