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 java.util.concurrent.Executor
25 import kotlin.test.fail
26 
27 /**
28  * Block until the specified Handler or HandlerThread becomes idle, or until timeoutMs has passed.
29  */
30 fun HandlerThread.waitForIdle(timeoutMs: Int) = threadHandler.waitForIdle(timeoutMs.toLong())
31 fun HandlerThread.waitForIdle(timeoutMs: Long) = threadHandler.waitForIdle(timeoutMs)
32 fun Handler.waitForIdle(timeoutMs: Int) = waitForIdle(timeoutMs.toLong())
33 fun Handler.waitForIdle(timeoutMs: Long) {
34     val cv = ConditionVariable(false)
35     post(cv::open)
36     if (!cv.block(timeoutMs)) {
37         fail("Handler did not become idle after ${timeoutMs}ms")
38     }
39 }
40 
41 /**
42  * Block until the given Serial Executor becomes idle, or until timeoutMs has passed.
43  */
44 fun waitForIdleSerialExecutor(executor: Executor, timeoutMs: Long) {
45     val cv = ConditionVariable()
46     executor.execute(cv::open)
47     if (!cv.block(timeoutMs)) {
48         fail("Executor did not become idle after ${timeoutMs}ms")
49     }
50 }
51