2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Modifications Copyright (C) 2019 IBM
10 * =============================================================================
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * ============LICENSE_END=========================================================
26 package org.onap.appc.pool;
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
31 import java.io.Closeable;
32 import java.io.IOException;
33 import java.lang.reflect.InvocationHandler;
34 import java.lang.reflect.Method;
35 import java.lang.reflect.Proxy;
36 import java.util.concurrent.atomic.AtomicBoolean;
39 * This class is used as a "wrapper" for any closeable elements that are cached in a pool. It is
40 * implemented as a dynamic proxy, so that it appears to be the same class of object to the client
41 * as the interface being cached. The generic type being cached MUST be an interface.
43 * @param <T> The generic type that we create a cached element for. This type is used to wrap
44 * instances of this type and expose access to the {@link java.io.Closeable} interface by
45 * using a dynamic proxy.
48 public class CachedElement<T extends Closeable>
49 implements Closeable, InvocationHandler, CacheManagement {
50 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(CachedElement.class);
53 * The pool that is managing this cached element
58 * The element that we are caching in the pool
63 * A thread-safe atomic indicator that tells us that the wrapped element has been released to
64 * the pool already, and not to do it again.
66 private AtomicBoolean released = new AtomicBoolean(false);
69 * Create a new instance of a cached element dynamic proxy for use in the pool.
71 * This returns an instance of the proxy to the caller that appears to be the same interface(s)
72 * as the object being cached. The dynamic proxy then intercepts all open and close semantics
73 * and directs that element to the pool.
76 * If the object being proxied does not implement the {@link CacheManagement} interface, then
77 * that interface is added to the dynamic proxy being created. This interface is actually
78 * implemented by the invocation handler (this object) for the proxy and allows direct access to
79 * the wrapped object inside the proxy.
82 * @param pool The pool that we are caching these elements within
83 * @param element The element actually being cached
84 * @param interfaces The interface list of interfaces the element must implement (usually one)
85 * @return The dynamic proxy
87 @SuppressWarnings("unchecked")
88 public static <T extends Closeable> T newInstance(Pool<T> pool, T element,
89 Class<?>[] interfaces) {
90 ClassLoader cl = element.getClass().getClassLoader();
91 CachedElement<T> ce = new CachedElement<>(pool, element);
92 boolean found = false;
93 for (Class<?> intf : interfaces) {
94 if (intf.isAssignableFrom(CacheManagement.class)) {
100 int length = found ? interfaces.length : interfaces.length + 1;
101 Class<?>[] proxyInterfaces = new Class[length];
102 System.arraycopy(interfaces, 0, proxyInterfaces, 0, interfaces.length);
105 proxyInterfaces[interfaces.length] = CacheManagement.class;
108 return (T) Proxy.newProxyInstance(cl, proxyInterfaces, ce);
112 * Construct a cached element and assign it to the pool as a free element
114 * @param pool The pool that the element will be managed within
115 * @param element The element we are caching
117 @SuppressWarnings("unchecked")
118 public CachedElement(Pool<T> pool, T element) {
120 this.element = element;
123 pool.release((T) this);
124 } catch (PoolDrainedException e) {
125 LOG.error("Pool is empty", e);
130 * This method delegates the close call to the actual wrapped element.
132 * NOTE: This is not the same method that is called by the dynamic proxy. This method is in
133 * place to satisfy the signature of the {@link java.io.Closeable} interface. If it were to be
134 * called directly, then we will delegate the close to the underlying context. However, when the
135 * cached element is called as a synamic proxy, entry is in the
136 * {@link #invoke(Object, Method, Object[])} method.
139 * @see java.io.Closeable#close()
142 public void close() throws IOException {
147 * This method is the magic part of dynamic proxies. When the caller makes a method call based
148 * on the interface being proxied, this method is given control. This informs us of the method
149 * and arguments of the call. The object reference is that of the dynamic proxy itself, which is
152 * Here we will check to see if the user is trying to close the "element" (the dynamic proxy
153 * acts like the wrapped element). If he is, then we don't really close it, but instead release
154 * the element that we are wrapping back to the free pool. Once this has happened, we mark the
155 * element as "closed" (from the perspective of this dynamic proxy) so that we wont try to
159 * If the method is the <code>equals</code> method then we assume that we are comparing the
160 * cached element in one dynamic proxy to the cached element in another. We execute the
161 * comparison between the cached elements, and not the dynamic proxies themselves. This
162 * preserves the allusion to the caller that the dynamic proxy is the object being wrapped.
165 * For convenience, we also implement the <code>getWrappedObject</code> method so that the
166 * dynamic proxy can be called to obtain the actual wrapped object if desired. Note, to use this
167 * method, the caller would have to invoke it through reflection.
170 * If the method being invoked is not one that we intercept, then we simply delegate that method
171 * onto the wrapped object.
174 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method,
175 * java.lang.Object[])
177 @SuppressWarnings({"unchecked", "nls"})
179 public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
180 Object result = null;
182 switch (method.getName()) {
184 if (released.compareAndSet(false, true) && !pool.isDrained()) {
185 pool.release((T) proxy);
189 CacheManagement cm = (CacheManagement) proxy;
190 T other = (T) cm.getWrappedObject();
191 result = element.equals(other);
193 case "getWrappedObject":
196 result = method.invoke(element, args);
204 * This method is used to be able to access the wrapped object underneath the dynamic proxy
206 * @see org.onap.appc.pool.CacheManagement#getWrappedObject()
209 public T getWrappedObject() {
213 @SuppressWarnings("nls")
215 public String toString() {
216 return element == null ? "null" : element.toString();