1 /* 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 17 package android.assist.common; 18 19 import java.util.concurrent.CountDownLatch; 20 import java.util.concurrent.TimeUnit; 21 22 /** 23 * A [CountDownLatch] that resets itself to [mCount] after every await call. 24 */ 25 public class AutoResetLatch { 26 27 private final int mCount; 28 private CountDownLatch mLatch; 29 30 public AutoResetLatch() { 31 this(1); 32 } 33 34 public AutoResetLatch(int count) { 35 mCount = count; 36 mLatch = new CountDownLatch(count); 37 } 38 39 public void await() throws InterruptedException { 40 try { 41 mLatch.await(); 42 } finally { 43 mLatch = new CountDownLatch(mCount); 44 } 45 } 46 47 public boolean await(long timeout, TimeUnit unit) throws InterruptedException { 48 try { 49 return mLatch.await(timeout, unit); 50 } finally { 51 mLatch = new CountDownLatch(mCount); 52 } 53 } 54 55 public void countDown() { 56 mLatch.countDown(); 57 } 58 } 59