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.common; 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 public final class BusyWaitUtils { 27 28 private static final long POLLING_INTERVAL = TimeUnit.MILLISECONDS.toMillis(50); 29 30 /** 31 * Callback interface for {@link #pollingCheck(PollingCondition, long, String)} and 32 * {@link #waitFor(PollingCondition, long)}. 33 */ 34 @FunctionalInterface 35 public interface PollingCondition { 36 /** 37 * Called back for polling check. 38 * 39 * @return {@code true} when the polling condition is met. 40 * @throws Exception when whatever unexpected problem happened. 41 */ check()42 boolean check() throws Exception; 43 } 44 45 // This is utility class, can't instantiate. BusyWaitUtils()46 private BusyWaitUtils() {} 47 48 /** 49 * Busy waiting until {@link PollingCondition#check()} returns {@code true}. 50 * @param condition {@link PollingCondition} to be checked. 51 * @param timeout milliseconds before time out happens. 52 * @param message when time out happens, {@link org.junit.Assert#fail(String)} is called with 53 * this message. 54 * @throws Exception 55 */ pollingCheck(PollingCondition condition, long timeout, String message)56 public static void pollingCheck(PollingCondition condition, long timeout, String message) 57 throws Exception { 58 if (waitFor(condition, timeout)) { 59 return; 60 } 61 fail(message); 62 } 63 64 /** 65 * Busy waiting until {@link PollingCondition#check()} returns {@code true}. 66 * @param condition {@link PollingCondition} to be checked. 67 * @param timeout milliseconds before time out happens. 68 * @return true when {@code condition} returns {@code true}, false when timed out. 69 * @throws Exception 70 */ waitFor(PollingCondition condition, long timeout)71 static boolean waitFor(PollingCondition condition, long timeout) throws Exception { 72 for (long remaining = timeout; remaining > 0; remaining -= POLLING_INTERVAL) { 73 if (condition.check()) { 74 return true; 75 } 76 Thread.sleep(POLLING_INTERVAL); 77 } 78 return false; 79 } 80 } 81