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