2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ============LICENSE_END=========================================================
26 package org.onap.appc.pool;
28 import java.io.Closeable;
29 import java.util.ArrayDeque;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.Deque;
33 import java.util.List;
34 import java.util.ListIterator;
35 import java.util.Properties;
36 import java.util.concurrent.atomic.AtomicBoolean;
37 import java.util.concurrent.locks.Lock;
38 import java.util.concurrent.locks.ReadWriteLock;
39 import java.util.concurrent.locks.ReentrantReadWriteLock;
42 * This class is used to manage a pool of things.
44 * The class is parameterized so that the type of objects maintained in the pool is definable by some provided type.
45 * This type must implement the <code>Comparable</code> interface so that it can be managed in the pool.
49 * The type of element being pooled
52 public class Pool<T extends Closeable> {
53 private Deque<T> free;
54 private List<T> allocated;
57 private Allocator<T> allocator;
58 private Destructor<T> destructor;
59 private ReadWriteLock lock;
60 private AtomicBoolean drained;
61 private Properties properties;
67 * The minimum size of the pool
69 * The maximum size of the pool, set to zero (0) for unbounded
70 * @throws PoolSpecificationException
71 * If the minimum size is less than 0, or if the max size is non-zero and less than the min size.
73 public Pool(int minPool, int maxPool) throws PoolSpecificationException {
76 throw new PoolSpecificationException(String.format("The minimum pool size must be a "
77 + "positive value or zero, %d is not valid.", minPool));
79 if (maxPool != 0 && maxPool < minPool) {
80 throw new PoolSpecificationException(String.format("The maximum pool size must be a "
81 + "positive value greater than the minimum size, or zero. %d is not valid.", maxPool));
84 this.minPool = minPool;
85 this.maxPool = maxPool;
87 properties = new Properties();
88 free = new ArrayDeque<T>();
89 allocated = new ArrayList<T>();
90 lock = new ReentrantReadWriteLock();
91 drained = new AtomicBoolean(false);
95 * Returns the amount of objects on the free collection
97 * @return The number of objects on the free collection
99 public int getFreeSize() {
100 Lock readLock = lock.readLock();
110 * Returns the value for a specified property of this pool, if defined.
113 * The key of the desired property
114 * @return The value of the property, or null if not defined
116 public String getProperty(String key) {
117 return properties.getProperty(key);
121 * Sets the value of the specified property or replaces it if it already exists
124 * The key of the property to be set
126 * The value to set the property to
128 public void setProperty(String key, String value) {
129 properties.setProperty(key, value);
133 * @return The properties object for the pool
135 public Properties getProperties() {
140 * Returns the number of objects that are currently allocated
142 * @return The allocate collection size
144 public int getAllocatedSize() {
145 Lock readLock = lock.readLock();
148 return allocated.size();
155 * @return the value of allocator
157 public Allocator<T> getAllocator() {
163 * the value for allocator
165 public void setAllocator(Allocator<T> allocator) {
166 this.allocator = allocator;
170 * @return the value of destructor
172 public Destructor<T> getDestructor() {
177 * @return the value of minPool
179 public int getMinPool() {
184 * @return the value of maxPool
186 public int getMaxPool() {
192 * the value for destructor
194 public void setDestructor(Destructor<T> destructor) {
195 this.destructor = destructor;
199 * Drains the pool, releasing and destroying all pooled objects, even if they are currently allocated.
201 public void drain() {
202 if (drained.compareAndSet(false, true)) {
203 Lock writeLock = lock.writeLock();
206 int size = getAllocatedSize();
208 * We can't use the "release" method call here because we are modifying the list we are iterating
210 ListIterator<T> it = allocated.listIterator();
211 while (it.hasNext()) {
216 size = getFreeSize();
225 * Returns an indication if the pool has been drained
227 * @return True indicates that the pool has been drained. Once a pool has been drained, it can no longer be used.
229 public boolean isDrained() {
230 return drained.get();
234 * Reserves an object of type T from the pool for the caller and returns it
236 * @return The object of type T to be used by the caller
237 * @throws PoolExtensionException
238 * If the pool cannot be extended
239 * @throws PoolDrainedException
240 * If the caller is trying to reserve an element from a drained pool
242 @SuppressWarnings("unchecked")
243 public T reserve() throws PoolExtensionException, PoolDrainedException {
245 throw new PoolDrainedException("The pool has been drained and cannot be used.");
249 Lock writeLock = lock.writeLock();
252 int freeSize = getFreeSize();
253 int allocatedSize = getAllocatedSize();
256 if (allocatedSize == 0) {
257 extend(minPool == 0 ? 1 : minPool);
258 } else if (allocatedSize >= maxPool && maxPool > 0) {
259 throw new PoolExtensionException(String.format("Unable to add "
260 + "more elements, pool is at maximum size of %d", maxPool));
266 obj = free.removeFirst();
273 * Now that we have the real object, lets wrap it in a dynamic proxy so that we can intercept the close call and
274 * just return the context to the free pool. obj.getClass().getInterfaces(). We need to find ALL interfaces that
275 * the object (and all superclasses) implement and have the proxy implement them too
277 Class<?> cls = obj.getClass();
279 List<Class<?>> interfaces = new ArrayList<Class<?>>();
280 while (!cls.equals(Object.class)) {
281 array = cls.getInterfaces();
282 for (Class<?> item : array) {
283 if (!interfaces.contains(item)) {
284 interfaces.add(item);
287 cls = cls.getSuperclass();
289 array = new Class<?>[interfaces.size()];
290 array = interfaces.toArray(array);
291 return CachedElement.newInstance(this, obj, array);
295 * releases the allocated object back to the free pool to be used by another request.
298 * The object to be returned to the pool
299 * @throws PoolDrainedException
300 * If the caller is trying to release an element to a drained pool
302 public void release(T obj) throws PoolDrainedException {
304 throw new PoolDrainedException("The pool has been drained and cannot be used.");
306 Lock writeLock = lock.writeLock();
309 if (allocated.remove(obj)) {
318 * Extend the free pool by some number of elements
321 * The number of elements to add to the pool
322 * @throws PoolExtensionException
323 * if the pool cannot be extended because no allocator has been specified.
325 private void extend(int count) throws PoolExtensionException {
326 if (allocator == null) {
327 throw new PoolExtensionException(String.format("Unable to extend pool "
328 + "because no allocator has been specified"));
330 Lock writeLock = lock.writeLock();
333 for (int index = 0; index < count; index++) {
334 T obj = allocator.allocate(this);
336 throw new PoolExtensionException(
337 "The allocator failed to allocate a new context to extend the pool.");
347 * Used to trim the free collection by some specified number of elements, or the free element count, whichever is
348 * less. The elements are removed from the end of the free element deque, thus trimming the oldest elements first.
351 * The number of elements to trim
353 private void trim(int count) {
354 Lock writeLock = lock.writeLock();
357 int trimCount = count;
358 if (getFreeSize() < count) {
359 trimCount = getFreeSize();
361 for (int i = 0; i < trimCount; i++) {
362 T obj = free.removeLast();
363 if (destructor != null) {
364 destructor.destroy(obj, this);