• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 The gRPC Authors
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 io.grpc.internal;
18 
19 import java.util.HashSet;
20 import javax.annotation.concurrent.NotThreadSafe;
21 
22 /**
23  * Aggregates the in-use state of a set of objects.
24  */
25 @NotThreadSafe
26 abstract class InUseStateAggregator<T> {
27 
28   private final HashSet<T> inUseObjects = new HashSet<T>();
29 
30   /**
31    * Update the in-use state of an object. Initially no object is in use.
32    *
33    * <p>This may call into {@link #handleInUse} or {@link #handleNotInUse} when appropriate.
34    */
updateObjectInUse(T object, boolean inUse)35   final void updateObjectInUse(T object, boolean inUse) {
36     int origSize = inUseObjects.size();
37     if (inUse) {
38       inUseObjects.add(object);
39       if (origSize == 0) {
40         handleInUse();
41       }
42     } else {
43       boolean removed = inUseObjects.remove(object);
44       if (removed && origSize == 1) {
45         handleNotInUse();
46       }
47     }
48   }
49 
isInUse()50   final boolean isInUse() {
51     return !inUseObjects.isEmpty();
52   }
53 
54   /**
55    * Called when the aggregated in-use state has changed to true, which means at least one object is
56    * in use.
57    */
handleInUse()58   abstract void handleInUse();
59 
60   /**
61    * Called when the aggregated in-use state has changed to false, which means no object is in use.
62    */
handleNotInUse()63   abstract void handleNotInUse();
64 }
65