1/*
2 * Copyright (C) 2015 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.tv.util;
18
19import android.os.Handler;
20import android.os.Looper;
21
22import java.util.List;
23import java.util.concurrent.AbstractExecutorService;
24import java.util.concurrent.TimeUnit;
25
26/**
27 * An executor service that executes its tasks on the main thread.
28 *
29 * Shutting down this executor is not supported.
30 */
31public class MainThreadExecutor extends AbstractExecutorService {
32
33    private final static MainThreadExecutor INSTANCE = new MainThreadExecutor();
34
35    public static MainThreadExecutor getInstance() {
36        return INSTANCE;
37    }
38
39    private final Handler mHandler = new Handler(Looper.getMainLooper());
40
41    @Override
42    public void execute(Runnable runnable) {
43        if (Looper.getMainLooper() == Looper.myLooper()) {
44            runnable.run();
45        } else {
46            mHandler.post(runnable);
47        }
48    }
49
50    /**
51     * Not supported and throws an exception when used.
52     */
53    @Override
54    @Deprecated
55    public void shutdown() {
56        throw new UnsupportedOperationException();
57    }
58
59    /**
60     * Not supported and throws an exception when used.
61     */
62    @Override
63    @Deprecated
64    public List<Runnable> shutdownNow() {
65        throw new UnsupportedOperationException();
66    }
67
68    @Override
69    public boolean isShutdown() {
70        return false;
71    }
72
73    @Override
74    public boolean isTerminated() {
75        return false;
76    }
77
78    /**
79     * Not supported and throws an exception when used.
80     */
81    @Override
82    @Deprecated
83    public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException {
84        throw new UnsupportedOperationException();
85    }
86}