blob: 861f45ee3c00dc466c0e7ba9cafea4802b322cee [file] [log] [blame]
Chalard Jean48c6c7d2020-06-25 23:39:15 +09001/*
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
Chalard Jeanb1856fe2020-06-26 00:42:01 +090017@file:JvmName("HandlerUtils")
18
Chalard Jean48c6c7d2020-06-25 23:39:15 +090019package com.android.testutils
20
21import android.os.ConditionVariable
22import android.os.Handler
23import android.os.HandlerThread
24import java.util.concurrent.Executor
Chalard Jean48c6c7d2020-06-25 23:39:15 +090025import kotlin.test.fail
26
27/**
28 * Block until the specified Handler or HandlerThread becomes idle, or until timeoutMs has passed.
29 */
30fun HandlerThread.waitForIdle(timeoutMs: Int) = threadHandler.waitForIdle(timeoutMs.toLong())
31fun HandlerThread.waitForIdle(timeoutMs: Long) = threadHandler.waitForIdle(timeoutMs)
32fun Handler.waitForIdle(timeoutMs: Int) = waitForIdle(timeoutMs.toLong())
33fun 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 */
44fun 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}