Fix request handler class error
[appc.git] / appc-common / src / main / java / org / onap / appc / pool / Pool.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
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
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
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.
20  * 
21  * ============LICENSE_END=========================================================
22  */
23
24
25
26 package org.onap.appc.pool;
27
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;
40
41 /**
42  * This class is used to manage a pool of things.
43  * <p>
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.
46  * </p>
47  * 
48  * @param <T>
49  *            The type of element being pooled
50  */
51
52 public class Pool<T extends Closeable> {
53     private Deque<T> free;
54     private List<T> allocated;
55     private int minPool;
56     private int maxPool;
57     private Allocator<T> allocator;
58     private Destructor<T> destructor;
59     private ReadWriteLock lock;
60     private AtomicBoolean drained;
61     private Properties properties;
62
63     /**
64      * Create the pool
65      *
66      * @param minPool
67      *            The minimum size of the pool
68      * @param maxPool
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.
72      */
73     public Pool(int minPool, int maxPool) throws PoolSpecificationException {
74
75         if (minPool < 0) {
76             throw new PoolSpecificationException(String.format("The minimum pool size must be a "
77                 + "positive value or zero, %d is not valid.", minPool));
78         }
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));
82         }
83
84         this.minPool = minPool;
85         this.maxPool = maxPool;
86
87         properties = new Properties();
88         free = new ArrayDeque<T>();
89         allocated = new ArrayList<T>();
90         lock = new ReentrantReadWriteLock();
91         drained = new AtomicBoolean(false);
92     }
93
94     /**
95      * Returns the amount of objects on the free collection
96      *
97      * @return The number of objects on the free collection
98      */
99     public int getFreeSize() {
100         Lock readLock = lock.readLock();
101         readLock.lock();
102         try {
103             return free.size();
104         } finally {
105             readLock.unlock();
106         }
107     }
108
109     /**
110      * Returns the value for a specified property of this pool, if defined.
111      * 
112      * @param key
113      *            The key of the desired property
114      * @return The value of the property, or null if not defined
115      */
116     public String getProperty(String key) {
117         return properties.getProperty(key);
118     }
119
120     /**
121      * Sets the value of the specified property or replaces it if it already exists
122      * 
123      * @param key
124      *            The key of the property to be set
125      * @param value
126      *            The value to set the property to
127      */
128     public void setProperty(String key, String value) {
129         properties.setProperty(key, value);
130     }
131
132     /**
133      * @return The properties object for the pool
134      */
135     public Properties getProperties() {
136         return properties;
137     }
138
139     /**
140      * Returns the number of objects that are currently allocated
141      *
142      * @return The allocate collection size
143      */
144     public int getAllocatedSize() {
145         Lock readLock = lock.readLock();
146         readLock.lock();
147         try {
148             return allocated.size();
149         } finally {
150             readLock.unlock();
151         }
152     }
153
154     /**
155      * @return the value of allocator
156      */
157     public Allocator<T> getAllocator() {
158         return allocator;
159     }
160
161     /**
162      * @param allocator
163      *            the value for allocator
164      */
165     public void setAllocator(Allocator<T> allocator) {
166         this.allocator = allocator;
167     }
168
169     /**
170      * @return the value of destructor
171      */
172     public Destructor<T> getDestructor() {
173         return destructor;
174     }
175
176     /**
177      * @return the value of minPool
178      */
179     public int getMinPool() {
180         return minPool;
181     }
182
183     /**
184      * @return the value of maxPool
185      */
186     public int getMaxPool() {
187         return maxPool;
188     }
189
190     /**
191      * @param destructor
192      *            the value for destructor
193      */
194     public void setDestructor(Destructor<T> destructor) {
195         this.destructor = destructor;
196     }
197
198     /**
199      * Drains the pool, releasing and destroying all pooled objects, even if they are currently allocated.
200      */
201     public void drain() {
202         if (drained.compareAndSet(false, true)) {
203             Lock writeLock = lock.writeLock();
204             writeLock.lock();
205             try {
206                 int size = getAllocatedSize();
207                 /*
208                  * We can't use the "release" method call here because we are modifying the list we are iterating
209                  */
210                 ListIterator<T> it = allocated.listIterator();
211                 while (it.hasNext()) {
212                     T obj = it.next();
213                     it.remove();
214                     free.addFirst(obj);
215                 }
216                 size = getFreeSize();
217                 trim(size);
218             } finally {
219                 writeLock.unlock();
220             }
221         }
222     }
223
224     /**
225      * Returns an indication if the pool has been drained
226      *
227      * @return True indicates that the pool has been drained. Once a pool has been drained, it can no longer be used.
228      */
229     public boolean isDrained() {
230         return drained.get();
231     }
232
233     /**
234      * Reserves an object of type T from the pool for the caller and returns it
235      *
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
241      */
242     @SuppressWarnings("unchecked")
243     public T reserve() throws PoolExtensionException, PoolDrainedException {
244         if (isDrained()) {
245             throw new PoolDrainedException("The pool has been drained and cannot be used.");
246         }
247
248         T obj = null;
249         Lock writeLock = lock.writeLock();
250         writeLock.lock();
251         try {
252             int freeSize = getFreeSize();
253             int allocatedSize = getAllocatedSize();
254
255             if (freeSize == 0) {
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));
261                 } else {
262                     extend(1);
263                 }
264             }
265
266             obj = free.removeFirst();
267             allocated.add(obj);
268         } finally {
269             writeLock.unlock();
270         }
271
272         /*
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
276          */
277         Class<?> cls = obj.getClass();
278         Class<?>[] array;
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);
285                 }
286             }
287             cls = cls.getSuperclass();
288         }
289         array = new Class<?>[interfaces.size()];
290         array = interfaces.toArray(array);
291         return CachedElement.newInstance(this, obj, array);
292     }
293
294     /**
295      * releases the allocated object back to the free pool to be used by another request.
296      *
297      * @param obj
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
301      */
302     public void release(T obj) throws PoolDrainedException {
303         if (isDrained()) {
304             throw new PoolDrainedException("The pool has been drained and cannot be used.");
305         }
306         Lock writeLock = lock.writeLock();
307         writeLock.lock();
308         try {
309             if (allocated.remove(obj)) {
310                 free.addFirst(obj);
311             }
312         } finally {
313             writeLock.unlock();
314         }
315     }
316
317     /**
318      * Extend the free pool by some number of elements
319      *
320      * @param count
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.
324      */
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"));
329         }
330         Lock writeLock = lock.writeLock();
331         writeLock.lock();
332         try {
333             for (int index = 0; index < count; index++) {
334                 T obj = allocator.allocate(this);
335                 if (obj == null) {
336                     throw new PoolExtensionException(
337                         "The allocator failed to allocate a new context to extend the pool.");
338                 }
339                 free.push(obj);
340             }
341         } finally {
342             writeLock.unlock();
343         }
344     }
345
346     /**
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.
349      *
350      * @param count
351      *            The number of elements to trim
352      */
353     private void trim(int count) {
354         Lock writeLock = lock.writeLock();
355         writeLock.lock();
356         try {
357             int trimCount = count;
358             if (getFreeSize() < count) {
359                 trimCount = getFreeSize();
360             }
361             for (int i = 0; i < trimCount; i++) {
362                 T obj = free.removeLast();
363                 if (destructor != null) {
364                     destructor.destroy(obj, this);
365                 }
366             }
367         } finally {
368             writeLock.unlock();
369         }
370     }
371 }