1 /*
2  * Copyright (C) 2017 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 android.inputmethodservice.cts.devicetest;
18 
19 import static org.junit.Assert.fail;
20 
21 import java.util.concurrent.TimeUnit;
22 
23 /**
24  * Utility class for busy waiting.
25  */
26 final class BusyWaitUtils {
27 
28     private static final long POLLING_INTERVAL = TimeUnit.MILLISECONDS.toMillis(50);
29 
30     @FunctionalInterface
31     interface PollingCondition {
check()32         boolean check() throws Exception;
33     }
34 
35     // This is utility class, can't instantiate.
BusyWaitUtils()36     private BusyWaitUtils() {}
37 
38     /**
39      * Busy waiting until {@link PollingCondition#check()} returns {@code true}.
40      * @param condition {@link PollingCondition} to be checked.
41      * @param timeout milliseconds before time out happens.
42      * @param message when time out happens, {@link org.junit.Assert#fail(String)} is called with
43      *                this message.
44      * @throws Exception
45      */
pollingCheck(final PollingCondition condition, final long timeout, final String message)46     static void pollingCheck(final PollingCondition condition, final long timeout,
47             final String message) throws Exception {
48         if (waitFor(condition, timeout)) {
49             return;
50         }
51         fail(message);
52     }
53 
54     /**
55      * Busy waiting until {@link PollingCondition#check()} returns {@code true}.
56      * @param condition {@link PollingCondition} to be checked.
57      * @param timeout milliseconds before time out happens.
58      * @return true when {@code condition} returns {@code true}, false when timed out.
59      * @throws Exception
60      */
waitFor(final PollingCondition condition, final long timeout)61     static boolean waitFor(final PollingCondition condition, final long timeout) throws Exception {
62         for (long remaining = timeout; remaining > 0; remaining -= POLLING_INTERVAL) {
63             if (condition.check()) {
64                 return true;
65             }
66             Thread.sleep(POLLING_INTERVAL);
67         }
68         return false;
69     }
70 }
71