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 
17 package com.android.tv.util;
18 
19 import android.os.Handler;
20 import android.os.Looper;
21 
22 import java.util.List;
23 import java.util.concurrent.AbstractExecutorService;
24 import 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  */
31 public class MainThreadExecutor extends AbstractExecutorService {
32 
33     private final static MainThreadExecutor INSTANCE = new MainThreadExecutor();
34 
getInstance()35     public static MainThreadExecutor getInstance() {
36         return INSTANCE;
37     }
38 
39     private final Handler mHandler = new Handler(Looper.getMainLooper());
40 
41     @Override
execute(Runnable runnable)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
shutdown()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
shutdownNow()64     public List<Runnable> shutdownNow() {
65         throw new UnsupportedOperationException();
66     }
67 
68     @Override
isShutdown()69     public boolean isShutdown() {
70         return false;
71     }
72 
73     @Override
isTerminated()74     public boolean isTerminated() {
75         return false;
76     }
77 
78     /**
79      * Not supported and throws an exception when used.
80      */
81     @Override
82     @Deprecated
awaitTermination(long l, TimeUnit timeUnit)83     public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException {
84         throw new UnsupportedOperationException();
85     }
86 }