1 /*
2  * Copyright (C) 2019 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 @file:JvmName("HandlerUtils")
18 
19 package com.android.testutils
20 
21 import android.os.ConditionVariable
22 import android.os.Handler
23 import android.os.HandlerThread
24 import android.util.Log
25 import com.android.testutils.FunctionalUtils.ThrowingRunnable
26 import com.android.testutils.FunctionalUtils.ThrowingSupplier
27 import java.lang.Exception
28 import java.util.concurrent.Executor
29 import kotlin.test.fail
30 
31 private const val TAG = "HandlerUtils"
32 
33 /**
34  * Block until the specified Handler or HandlerThread becomes idle, or until timeoutMs has passed.
35  */
HandlerThreadnull36 fun HandlerThread.waitForIdle(timeoutMs: Int) = threadHandler.waitForIdle(timeoutMs.toLong())
37 fun HandlerThread.waitForIdle(timeoutMs: Long) = threadHandler.waitForIdle(timeoutMs)
38 fun Handler.waitForIdle(timeoutMs: Int) = waitForIdle(timeoutMs.toLong())
39 fun Handler.waitForIdle(timeoutMs: Long) {
40     val cv = ConditionVariable(false)
41     post(cv::open)
42     if (!cv.block(timeoutMs)) {
43         fail("Handler did not become idle after ${timeoutMs}ms")
44     }
45 }
46 
47 /**
48  * Block until the given Serial Executor becomes idle, or until timeoutMs has passed.
49  */
waitForIdleSerialExecutornull50 fun waitForIdleSerialExecutor(executor: Executor, timeoutMs: Long) {
51     val cv = ConditionVariable()
52     executor.execute(cv::open)
53     if (!cv.block(timeoutMs)) {
54         fail("Executor did not become idle after ${timeoutMs}ms")
55     }
56 }
57 
58 /**
59  * Executes a block of code that returns a value, making its side effects visible on the caller and
60  * the handler thread.
61  *
62  * After this function returns, the side effects of the passed block of code are guaranteed to be
63  * observed both on the thread running the handler and on the thread running this method.
64  * To achieve this, this method runs the passed block on the handler and blocks this thread
65  * until it's executed, so keep in mind this method will block, (including, if the handler isn't
66  * running, blocking forever).
67  */
visibleOnHandlerThreadnull68 fun <T> visibleOnHandlerThread(handler: Handler, supplier: ThrowingSupplier<T>): T {
69     val cv = ConditionVariable()
70     var rv: Result<T> = Result.failure(RuntimeException("Not run"))
71     handler.post {
72         try {
73             rv = Result.success(supplier.get())
74         } catch (exception: Exception) {
75             Log.e(TAG, "visibleOnHandlerThread caught exception", exception)
76             rv = Result.failure(exception)
77         }
78         cv.open()
79     }
80     // After block() returns, the handler thread has seen the change (since it ran it)
81     // and this thread also has seen the change (since cv.open() happens-before cv.block()
82     // returns).
83     cv.block()
84     return rv.getOrThrow()
85 }
86 
87 /** Overload of visibleOnHandlerThread but executes a block of code that does not return a value. */
visibleOnHandlerThreadnull88 inline fun visibleOnHandlerThread(handler: Handler, r: ThrowingRunnable){
89     visibleOnHandlerThread(handler, ThrowingSupplier<Unit> { r.run() })
90 }
91