|
15 | 15 | * This is done via a dynamic proxy to preserve all interfaces of the wrapped handler. |
16 | 16 | */ |
17 | 17 | public class ReleasePermitOnComplete { |
18 | | - /** |
19 | | - * Wrap handler to release the permit of the semaphore on {@link AsyncHandler#onCompleted()}. |
20 | | - */ |
21 | | - public static <T> AsyncHandler<T> wrap(final AsyncHandler<T> handler, final Semaphore available) { |
22 | | - Class<?> handlerClass = handler.getClass(); |
23 | | - ClassLoader classLoader = handlerClass.getClassLoader(); |
24 | | - Class<?>[] interfaces = allInterfaces(handlerClass); |
25 | 18 |
|
26 | | - return (AsyncHandler<T>) Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() { |
27 | | - @Override |
28 | | - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { |
29 | | - try { |
30 | | - return method.invoke(handler, args); |
31 | | - } finally { |
32 | | - if ("onCompleted".equals(method.getName())) { |
33 | | - available.release(); |
34 | | - } |
| 19 | + /** |
| 20 | + * Wrap handler to release the permit of the semaphore on {@link AsyncHandler#onCompleted()}. |
| 21 | + */ |
| 22 | + @SuppressWarnings("unchecked") |
| 23 | + public static <T> AsyncHandler<T> wrap(final AsyncHandler<T> handler, final Semaphore available) { |
| 24 | + Class<?> handlerClass = handler.getClass(); |
| 25 | + ClassLoader classLoader = handlerClass.getClassLoader(); |
| 26 | + Class<?>[] interfaces = allInterfaces(handlerClass); |
| 27 | + |
| 28 | + return (AsyncHandler<T>) Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() { |
| 29 | + @Override |
| 30 | + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { |
| 31 | + try { |
| 32 | + return method.invoke(handler, args); |
| 33 | + } finally { |
| 34 | + if ("onCompleted".equals(method.getName())) { |
| 35 | + available.release(); |
| 36 | + } |
| 37 | + } |
35 | 38 | } |
36 | | - } |
37 | | - }); |
38 | | - } |
| 39 | + }); |
| 40 | + } |
39 | 41 |
|
40 | | - /** |
41 | | - * Extract all interfaces of a class. |
42 | | - */ |
43 | | - static Class<?>[] allInterfaces(Class<?> handlerClass) { |
44 | | - Set<Class<?>> allInterfaces = new HashSet<>(); |
45 | | - for (Class<?> clazz = handlerClass; clazz != null; clazz = clazz.getSuperclass()) { |
46 | | - Collections.addAll(allInterfaces, clazz.getInterfaces()); |
47 | | - } |
48 | | - return allInterfaces.toArray(new Class[allInterfaces.size()]); |
49 | | - } |
| 42 | + /** |
| 43 | + * Extract all interfaces of a class. |
| 44 | + */ |
| 45 | + static Class<?>[] allInterfaces(Class<?> handlerClass) { |
| 46 | + Set<Class<?>> allInterfaces = new HashSet<>(); |
| 47 | + for (Class<?> clazz = handlerClass; clazz != null; clazz = clazz.getSuperclass()) { |
| 48 | + Collections.addAll(allInterfaces, clazz.getInterfaces()); |
| 49 | + } |
| 50 | + return allInterfaces.toArray(new Class[allInterfaces.size()]); |
| 51 | + } |
50 | 52 | } |
0 commit comments