1 /*
2  * Copyright (C) 2023 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.devicelockcontroller.util;
18 
19 import android.os.Looper;
20 
21 /** A utility class that asserts worker/main threads */
22 public final class ThreadAsserts {
23 
ThreadAsserts()24     private ThreadAsserts() {}
25 
26     /**
27      * Assert that calling thread is not the main thread. If the calling thread is main thread, an
28      * {@link IllegalStateException} will be thrown.
29      *
30      * @param methodName The name of the method which will show up in the log if an exception is
31      *                   thrown.
32      */
assertWorkerThread(String methodName)33     public static void assertWorkerThread(String methodName) {
34         if (Looper.getMainLooper().isCurrentThread()) {
35             throw new IllegalStateException("Can not invoke " + methodName + " on the main thread");
36         }
37     }
38 
39     /**
40      * Assert that calling thread is the main thread. If the calling thread is not the main thread,
41      * an {@link IllegalStateException} will be thrown.
42      *
43      * @param methodName The name of the method which will show up in the log if an exception is
44      *                   thrown.
45      */
assertMainThread(String methodName)46     public static void assertMainThread(String methodName) {
47         if (!Looper.getMainLooper().isCurrentThread()) {
48             throw new IllegalStateException(
49                     "Can not invoke " + methodName + " on a background thread");
50         }
51     }
52 }
53