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 java.io.Closeable;
29 import java.io.IOException;
30 import java.lang.reflect.InvocationHandler;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.Proxy;
33 import java.util.concurrent.atomic.AtomicBoolean;
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
38 * This class is used as a "wrapper" for any closeable elements that are cached in a pool. It is
39 * implemented as a dynamic proxy, so that it appears to be the same class of object to the client
40 * as the interface being cached. The generic type being cached MUST be an interface.
42 * @param <T> The generic type that we create a cached element for. This type is used to wrap
43 * instances of this type and expose access to the {@link java.io.Closeable} interface by
44 * using a dynamic proxy.
47 public class CachedElement<T extends Closeable>
48 implements Closeable, InvocationHandler, CacheManagement {
49 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(CachedElement.class);
52 * The pool that is managing this cached element
57 * The element that we are caching in the pool
62 * A thread-safe atomic indicator that tells us that the wrapped element has been released to
63 * the pool already, and not to do it again.
65 private AtomicBoolean released = new AtomicBoolean(false);
68 * Create a new instance of a cached element dynamic proxy for use in the pool.
70 * This returns an instance of the proxy to the caller that appears to be the same interface(s)
71 * as the object being cached. The dynamic proxy then intercepts all open and close semantics
72 * and directs that element to the pool.
75 * If the object being proxied does not implement the {@link CacheManagement} interface, then
76 * that interface is added to the dynamic proxy being created. This interface is actually
77 * implemented by the invocation handler (this object) for the proxy and allows direct access to
78 * the wrapped object inside the proxy.
81 * @param pool The pool that we are caching these elements within
82 * @param element The element actually being cached
83 * @param interfaces The interface list of interfaces the element must implement (usually one)
84 * @return The dynamic proxy
86 @SuppressWarnings("unchecked")
87 public static <T extends Closeable> T newInstance(Pool<T> pool, T element,
88 Class<?>[] interfaces) {
89 ClassLoader cl = element.getClass().getClassLoader();
90 CachedElement<T> ce = new CachedElement<>(pool, element);
91 boolean found = false;
92 for (Class<?> intf : interfaces) {
93 if (intf.getName().equals(CacheManagement.class.getName())) {
99 int length = found ? interfaces.length : interfaces.length + 1;
100 Class<?>[] proxyInterfaces = new Class[length];
101 System.arraycopy(interfaces, 0, proxyInterfaces, 0, interfaces.length);
104 proxyInterfaces[interfaces.length] = CacheManagement.class;
107 return (T) Proxy.newProxyInstance(cl, proxyInterfaces, ce);
111 * Construct a cached element and assign it to the pool as a free element
113 * @param pool The pool that the element will be managed within
114 * @param element The element we are caching
116 @SuppressWarnings("unchecked")
117 public CachedElement(Pool<T> pool, T element) {
119 this.element = element;
122 pool.release((T) this);
123 } catch (PoolDrainedException e) {
124 LOG.error("Pool is empty", e);
129 * This method delegates the close call to the actual wrapped element.
131 * NOTE: This is not the same method that is called by the dynamic proxy. This method is in
132 * place to satisfy the signature of the {@link java.io.Closeable} interface. If it were to be
133 * called directly, then we will delegate the close to the underlying context. However, when the
134 * cached element is called as a synamic proxy, entry is in the
135 * {@link #invoke(Object, Method, Object[])} method.
138 * @see java.io.Closeable#close()
141 public void close() throws IOException {
146 * This method is the magic part of dynamic proxies. When the caller makes a method call based
147 * on the interface being proxied, this method is given control. This informs us of the method
148 * and arguments of the call. The object reference is that of the dynamic proxy itself, which is
151 * Here we will check to see if the user is trying to close the "element" (the dynamic proxy
152 * acts like the wrapped element). If he is, then we don't really close it, but instead release
153 * the element that we are wrapping back to the free pool. Once this has happened, we mark the
154 * element as "closed" (from the perspective of this dynamic proxy) so that we wont try to
158 * If the method is the <code>equals</code> method then we assume that we are comparing the
159 * cached element in one dynamic proxy to the cached element in another. We execute the
160 * comparison between the cached elements, and not the dynamic proxies themselves. This
161 * preserves the allusion to the caller that the dynamic proxy is the object being wrapped.
164 * For convenience, we also implement the <code>getWrappedObject</code> method so that the
165 * dynamic proxy can be called to obtain the actual wrapped object if desired. Note, to use this
166 * method, the caller would have to invoke it through reflection.
169 * If the method being invoked is not one that we intercept, then we simply delegate that method
170 * onto the wrapped object.
173 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method,
174 * java.lang.Object[])
176 @SuppressWarnings({"unchecked", "nls"})
178 public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
179 Object result = null;
181 switch (method.getName()) {
183 if (released.compareAndSet(false, true)) {
184 if (!pool.isDrained()) {
185 pool.release((T) proxy);
190 CacheManagement cm = (CacheManagement) proxy;
191 T other = (T) cm.getWrappedObject();
192 result = element.equals(other);
194 case "getWrappedObject":
197 result = method.invoke(element, args);
205 * This method is used to be able to access the wrapped object underneath the dynamic proxy
207 * @see org.onap.appc.pool.CacheManagement#getWrappedObject()
210 public T getWrappedObject() {
214 @SuppressWarnings("nls")
216 public String toString() {
217 return element == null ? "null" : element.toString();