1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.maven.surefire.extensions.util;
20
21 import javax.annotation.Nonnegative;
22 import javax.annotation.Nonnull;
23
24 import java.io.Closeable;
25 import java.io.IOException;
26
27 /**
28 * Decrements {@code countdown} and calls {@code closeable} if reached zero.
29 */
30 public final class CountdownCloseable implements Closeable {
31 private final Closeable closeable;
32 private volatile int countdown;
33
34 public CountdownCloseable(@Nonnull Closeable closeable, @Nonnegative int countdown) {
35 this.closeable = closeable;
36 this.countdown = countdown;
37 }
38
39 @Override
40 public synchronized void close() throws IOException {
41 if (--countdown == 0) {
42 try {
43 closeable.close();
44 } finally {
45 notifyAll();
46 }
47 }
48 }
49
50 /**
51 * Waiting for one Thread in {@link CommandlineExecutor#awaitExit()}.
52 *
53 * @throws InterruptedException see {@link Object#wait()}
54 */
55 public synchronized void awaitClosed() throws InterruptedException {
56 if (countdown > 0) {
57 wait();
58 }
59 }
60 }