2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
24 package org.openecomp.appc.pool;
26 import java.io.Closeable;
27 import java.util.ArrayDeque;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.Deque;
31 import java.util.List;
32 import java.util.ListIterator;
33 import java.util.Properties;
34 import java.util.concurrent.atomic.AtomicBoolean;
35 import java.util.concurrent.locks.Lock;
36 import java.util.concurrent.locks.ReadWriteLock;
37 import java.util.concurrent.locks.ReentrantReadWriteLock;
40 * This class is used to manage a pool of things.
42 * The class is parameterized so that the type of objects maintained in the pool is definable by some provided type.
43 * This type must implement the <code>Comparable</code> interface so that it can be managed in the pool.
47 * The type of element being pooled
50 public class Pool<T extends Closeable> {
51 private Deque<T> free;
52 private List<T> allocated;
55 private Allocator<T> allocator;
56 private Destructor<T> destructor;
57 private ReadWriteLock lock;
58 private AtomicBoolean drained;
59 private Properties properties;
65 * The minimum size of the pool
67 * The maximum size of the pool, set to zero (0) for unbounded
68 * @throws PoolSpecificationException
69 * If the minimum size is less than 0, or if the max size is non-zero and less than the min size.
71 public Pool(int minPool, int maxPool) throws PoolSpecificationException {
74 throw new PoolSpecificationException(String.format("The minimum pool size must be a "
75 + "positive value or zero, %d is not valid.", minPool));
77 if (maxPool != 0 && maxPool < minPool) {
78 throw new PoolSpecificationException(String.format("The maximum pool size must be a "
79 + "positive value greater than the minimum size, or zero. %d is not valid.", maxPool));
82 this.minPool = minPool;
83 this.maxPool = maxPool;
85 properties = new Properties();
86 free = new ArrayDeque<T>();
87 allocated = new ArrayList<T>();
88 lock = new ReentrantReadWriteLock();
89 drained = new AtomicBoolean(false);
93 * Returns the amount of objects on the free collection
95 * @return The number of objects on the free collection
97 public int getFreeSize() {
98 Lock readLock = lock.readLock();
108 * Returns the value for a specified property of this pool, if defined.
111 * The key of the desired property
112 * @return The value of the property, or null if not defined
114 public String getProperty(String key) {
115 return properties.getProperty(key);
119 * Sets the value of the specified property or replaces it if it already exists
122 * The key of the property to be set
124 * The value to set the property to
126 public void setProperty(String key, String value) {
127 properties.setProperty(key, value);
131 * @return The properties object for the pool
133 public Properties getProperties() {
138 * Returns the number of objects that are currently allocated
140 * @return The allocate collection size
142 public int getAllocatedSize() {
143 Lock readLock = lock.readLock();
146 return allocated.size();
153 * @return the value of allocator
155 public Allocator<T> getAllocator() {
161 * the value for allocator
163 public void setAllocator(Allocator<T> allocator) {
164 this.allocator = allocator;
168 * @return the value of destructor
170 public Destructor<T> getDestructor() {
175 * @return the value of minPool
177 public int getMinPool() {
182 * @return the value of maxPool
184 public int getMaxPool() {
190 * the value for destructor
192 public void setDestructor(Destructor<T> destructor) {
193 this.destructor = destructor;
197 * Drains the pool, releasing and destroying all pooled objects, even if they are currently allocated.
199 public void drain() {
200 if (drained.compareAndSet(false, true)) {
201 Lock writeLock = lock.writeLock();
204 int size = getAllocatedSize();
206 * We can't use the "release" method call here because we are modifying the list we are iterating
208 ListIterator<T> it = allocated.listIterator();
209 while (it.hasNext()) {
214 size = getFreeSize();
223 * Returns an indication if the pool has been drained
225 * @return True indicates that the pool has been drained. Once a pool has been drained, it can no longer be used.
227 public boolean isDrained() {
228 return drained.get();
232 * Reserves an object of type T from the pool for the caller and returns it
234 * @return The object of type T to be used by the caller
235 * @throws PoolExtensionException
236 * If the pool cannot be extended
237 * @throws PoolDrainedException
238 * If the caller is trying to reserve an element from a drained pool
240 @SuppressWarnings("unchecked")
241 public T reserve() throws PoolExtensionException, PoolDrainedException {
243 throw new PoolDrainedException("The pool has been drained and cannot be used.");
247 Lock writeLock = lock.writeLock();
250 int freeSize = getFreeSize();
251 int allocatedSize = getAllocatedSize();
254 if (allocatedSize == 0) {
255 extend(minPool == 0 ? 1 : minPool);
256 } else if (allocatedSize >= maxPool && maxPool > 0) {
257 throw new PoolExtensionException(String.format("Unable to add "
258 + "more elements, pool is at maximum size of %d", maxPool));
264 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);