• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 Google LLC
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  *   https://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 package com.google.android.enterprise.connectedapps.testing;
17 
18 /** Utility for blocking a thread while polling for a state. */
19 public class BlockingPoll {
20 
21   /** Interface implemented when using {@link #poll(BooleanSupplier, long, long)}. */
22   public interface BooleanSupplier {
getAsBoolean()23     boolean getAsBoolean();
24   }
25 
26   /**
27    * Poll for a state at a given frequency while blocking the thread.
28    *
29    * @param func returns true when the polling condition is met. False otherwise
30    * @param pollFrequency The number of milliseconds to wait between calling {@code func}
31    * @param timeoutMillis The maximum number of milliseconds before an {@link
32    *     IllegalStateException} is thrown.
33    */
poll(BooleanSupplier func, long pollFrequency, long timeoutMillis)34   public static void poll(BooleanSupplier func, long pollFrequency, long timeoutMillis) {
35     long endTime = System.currentTimeMillis() + timeoutMillis;
36     while (!func.getAsBoolean() && System.currentTimeMillis() < endTime) {
37       try {
38         Thread.sleep(pollFrequency);
39       } catch (InterruptedException e) {
40         throw new IllegalStateException("Sleep interrupted", e);
41       }
42     }
43 
44     if (!func.getAsBoolean()) {
45       throw new IllegalStateException("Timeout after " + timeoutMillis);
46     }
47   }
48 
BlockingPoll()49   private BlockingPoll() {}
50 }
51