MainThread.java revision 386c5b885b99f67f9c0a7380f4be153f28333089
1/* 2 * Copyright (C) 2014 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.camera.async; 18 19import android.os.Handler; 20import android.os.Looper; 21 22import com.google.common.annotations.VisibleForTesting; 23 24import javax.annotation.Nonnull; 25 26import static com.google.common.base.Preconditions.checkState; 27 28public class MainThread extends HandlerExecutor { 29 private MainThread(Handler handler) { 30 super(handler); 31 } 32 33 public static MainThread create() { 34 return new MainThread(new Handler(Looper.getMainLooper())); 35 } 36 37 /** 38 * Caches whether or not the current thread is the main thread. 39 */ 40 private static final ThreadLocal<Boolean> sIsMainThread = new ThreadLocal<Boolean>() { 41 @Override 42 protected Boolean initialValue() { 43 return Looper.getMainLooper().getThread() == Thread.currentThread(); 44 } 45 }; 46 47 /** 48 * Asserts that the current thread is the main thread. 49 */ 50 public static void checkMainThread() { 51 checkState(sIsMainThread.get(), "Not main thread."); 52 } 53 54 /** 55 * Returns a fake MainThreadExecutor which executes immediately. 56 */ 57 @VisibleForTesting 58 public static MainThread createFakeForTesting() { 59 return new MainThread(null) { 60 @Override 61 public void execute(@Nonnull Runnable runnable) { 62 // 63 sIsMainThread.set(true); 64 try { 65 runnable.run(); 66 } finally { 67 sIsMainThread.set(false); 68 } 69 } 70 }; 71 } 72} 73