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 package com.android.dialer.common.concurrent; 17 18 import com.google.common.util.concurrent.AbstractListeningExecutorService; 19 import com.google.common.util.concurrent.ListenableFuture; 20 import com.google.common.util.concurrent.SettableFuture; 21 import java.util.List; 22 import java.util.concurrent.Callable; 23 import java.util.concurrent.TimeUnit; 24 import javax.inject.Inject; 25 26 /** 27 * An ExecutorService that delegates to the UI thread. Rejects attempts to shut down, and all 28 * shutdown related APIs are unimplemented. 29 * 30 */ 31 public class UiThreadExecutor extends AbstractListeningExecutorService { 32 33 @Inject UiThreadExecutor()34 public UiThreadExecutor() {} 35 36 @Override shutdown()37 public void shutdown() { 38 throw new UnsupportedOperationException(); 39 } 40 41 @Override shutdownNow()42 public List<Runnable> shutdownNow() { 43 throw new UnsupportedOperationException(); 44 } 45 46 @Override isShutdown()47 public boolean isShutdown() { 48 return false; 49 } 50 51 @Override isTerminated()52 public boolean isTerminated() { 53 return false; 54 } 55 56 @Override awaitTermination(long l, TimeUnit timeUnit)57 public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException { 58 throw new UnsupportedOperationException(); 59 } 60 61 @Override submit(final Callable<V> task)62 public <V> ListenableFuture<V> submit(final Callable<V> task) { 63 final SettableFuture<V> resultFuture = SettableFuture.create(); 64 ThreadUtil.postOnUiThread( 65 () -> { 66 try { 67 resultFuture.set(task.call()); 68 } catch (Exception e) { 69 // uncaught exceptions on the UI thread should crash the app 70 resultFuture.setException(e); 71 throw new RuntimeException(e); 72 } 73 }); 74 return resultFuture; 75 } 76 77 @Override execute(final Runnable runnable)78 public void execute(final Runnable runnable) { 79 ThreadUtil.postOnUiThread(runnable); 80 } 81 } 82