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.Collections; 20 import java.util.IdentityHashMap; 21 import java.util.Set; 22 import javax.annotation.concurrent.NotThreadSafe; 23 24 /** 25 * Aggregates the in-use state of a set of objects. 26 */ 27 @NotThreadSafe 28 public abstract class InUseStateAggregator<T> { 29 30 private final Set<T> inUseObjects = Collections.newSetFromMap(new IdentityHashMap<T,Boolean>()); 31 32 /** 33 * Update the in-use state of an object. Initially no object is in use. 34 * 35 * <p>This may call into {@link #handleInUse} or {@link #handleNotInUse} when appropriate. 36 */ updateObjectInUse(T object, boolean inUse)37 public final void updateObjectInUse(T object, boolean inUse) { 38 int origSize = inUseObjects.size(); 39 if (inUse) { 40 inUseObjects.add(object); 41 if (origSize == 0) { 42 handleInUse(); 43 } 44 } else { 45 boolean removed = inUseObjects.remove(object); 46 if (removed && origSize == 1) { 47 handleNotInUse(); 48 } 49 } 50 } 51 isInUse()52 public final boolean isInUse() { 53 return !inUseObjects.isEmpty(); 54 } 55 56 /** 57 * Returns {@code true} if any of the given objects are in use. 58 * 59 * @param objects The objects to consider. 60 * @return {@code true} if any of the given objects are in use. 61 */ anyObjectInUse(Object... objects)62 public final boolean anyObjectInUse(Object... objects) { 63 for (Object object : objects) { 64 if (inUseObjects.contains(object)) { 65 return true; 66 } 67 } 68 return false; 69 } 70 71 /** 72 * Called when the aggregated in-use state has changed to true, which means at least one object is 73 * in use. 74 */ handleInUse()75 protected abstract void handleInUse(); 76 77 /** 78 * Called when the aggregated in-use state has changed to false, which means no object is in use. 79 */ handleNotInUse()80 protected abstract void handleNotInUse(); 81 } 82