blob: 04a59c9f62be24a393bced32de708a0312cfb798 [file] [log] [blame]
Madan Jampani7a7ef6d2016-01-26 22:01:13 -08001/*
2 * Copyright 2016 Open Networking Laboratory
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 */
16package org.onlab.util;
17
18import java.util.concurrent.atomic.AtomicLong;
19import java.util.function.Consumer;
20
21import static com.google.common.base.Preconditions.checkNotNull;
22import static com.google.common.base.Preconditions.checkState;
23
24/**
25 * A synchronization utility that defers invocation of a {@link Consumer consumer}
26 * callback until a set number of actions tracked by a {@code long} counter complete.
27 * <p>
28 * Each completion is recorded by invoking the {@link CountDownCompleter#countDown countDown}
29 * method. When the total number of completions is equal to the preset counter value,
30 * this instance is marked as completed and the callback invoked by supplying the object
31 * held by this instance.
32 *
33 * @param <T> object type
34 */
35public final class CountDownCompleter<T> {
36
37 private final T object;
38 private final Consumer<T> onCompleteCallback;
39 private final AtomicLong counter;
40
41 /**
42 * Constructor.
43 * @param object object
44 * @param count total number of times countDown must be invoked for this completer to complete
45 * @param onCompleteCallback callback to invoke when completer is completed
46 */
47 public CountDownCompleter(T object, long count, Consumer<T> onCompleteCallback) {
48 checkState(count > 0, "count must be positive");
49 this.counter = new AtomicLong(count);
50 this.object = checkNotNull(object);
51 this.onCompleteCallback = checkNotNull(onCompleteCallback);
52 }
53
54 /**
55 * Returns the object.
56 * @return object
57 */
58 public T object() {
59 return object;
60 }
61
62 /**
63 * Records a single completion.
64 * <p>
65 * If this instance has already completed, this method has no effect
66 */
67 public void countDown() {
68 if (counter.decrementAndGet() == 0) {
69 onCompleteCallback.accept(object);
70 }
71 }
72
73 /**
74 * Returns if this instance has completed.
75 * @return {@code true} if completed
76 */
77 public boolean isComplete() {
78 return counter.get() <= 0;
79 }
80}