1/*
2 * Copyright (C) 2017 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 androidx.arch.core.executor;
18
19import android.os.Handler;
20import android.os.Looper;
21
22import androidx.annotation.Nullable;
23import androidx.annotation.RestrictTo;
24
25import java.util.concurrent.ExecutorService;
26import java.util.concurrent.Executors;
27import java.util.concurrent.ThreadFactory;
28import java.util.concurrent.atomic.AtomicInteger;
29
30/**
31 * @hide
32 */
33@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
34public class DefaultTaskExecutor extends TaskExecutor {
35
36    private final Object mLock = new Object();
37
38    private final ExecutorService mDiskIO = Executors.newFixedThreadPool(2, new ThreadFactory() {
39        private static final String THREAD_NAME_STEM = "arch_disk_io_%d";
40
41        private final AtomicInteger mThreadId = new AtomicInteger(0);
42
43        @Override
44        public Thread newThread(Runnable r) {
45            Thread t = new Thread(r);
46            t.setName(String.format(THREAD_NAME_STEM, mThreadId.getAndIncrement()));
47            return t;
48        }
49    });
50
51    @Nullable
52    private volatile Handler mMainHandler;
53
54    @Override
55    public void executeOnDiskIO(Runnable runnable) {
56        mDiskIO.execute(runnable);
57    }
58
59    @Override
60    public void postToMainThread(Runnable runnable) {
61        if (mMainHandler == null) {
62            synchronized (mLock) {
63                if (mMainHandler == null) {
64                    mMainHandler = new Handler(Looper.getMainLooper());
65                }
66            }
67        }
68        //noinspection ConstantConditions
69        mMainHandler.post(runnable);
70    }
71
72    @Override
73    public boolean isMainThread() {
74        return Looper.getMainLooper().getThread() == Thread.currentThread();
75    }
76}
77