1 /*
2  * Copyright (C) 2021 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 libcore.java.util.concurrent;
18 
19 import static org.junit.Assert.fail;
20 
21 import java.time.Duration;
22 import java.util.function.BooleanSupplier;
23 
24 class TestUtils {
25 
26     public static final long MILLIS_TO_NANO = (1000 * 1000);
27 
joinThreadOrFail(long timeoutMillis, Thread thread)28     public static void joinThreadOrFail(long timeoutMillis, Thread thread) {
29         try {
30             thread.join(timeoutMillis);
31         } catch (InterruptedException fail) {
32             fail("InterruptedException when joining thread");
33         } finally {
34             if (thread.getState() != Thread.State.TERMINATED) {
35                 thread.interrupt();
36                 fail("timed out waiting to join thread");
37             }
38         }
39     }
40 
waitWhileTrueOrTimeout(Duration timeout, BooleanSupplier conditionFn)41     public static boolean waitWhileTrueOrTimeout(Duration timeout, BooleanSupplier conditionFn) {
42         Duration startTime = Duration.ofNanos(System.nanoTime());
43         while (conditionFn.getAsBoolean()) {
44             Duration now = Duration.ofNanos(System.nanoTime());
45             if (now.minus(startTime).compareTo(timeout) >= 0) {
46                 return false;
47             }
48             Thread.yield();
49         }
50         return true;
51     }
52 
53 }
54