Debian Codegraph @

src/main/java/com/jcabi/aspects/aj/MethodAsyncRunner.java

raw
1 /**
2 * Copyright (c) 2012-2017, jcabi.com
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met: 1) Redistributions of source code must retain the above
8 * copyright notice, this list of conditions and the following
9 * disclaimer. 2) Redistributions in binary form must reproduce the above
10 * copyright notice, this list of conditions and the following
11 * disclaimer in the documentation and/or other materials provided
12 * with the distribution. 3) Neither the name of the jcabi.com nor
13 * the names of its contributors may be used to endorse or promote
14 * products derived from this software without specific prior written
15 * permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
19 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28 * OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30 package com.jcabi.aspects.aj;
31
32 import java.util.concurrent.Callable;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.Future;
36 import org.aspectj.lang.ProceedingJoinPoint;
37 import org.aspectj.lang.annotation.Around;
38 import org.aspectj.lang.annotation.Aspect;
39 import org.aspectj.lang.reflect.MethodSignature;
40
41 /**
42 * Execute method asynchronously.
43 *
44 * <p>It is an AspectJ aspect and you are not supposed to use it directly. It
45 * is instantiated by AspectJ runtime framework when your code is annotated
46 * with {@link com.jcabi.aspects.Async} annotation.
47 *
48 * @author Carlos Miranda ([email protected])
49 * @version $Id: 972751382ebf0b8001b87df907717122a5ad4664 $
50 * @since 0.16
51 */
52 @Aspect
53 public final class MethodAsyncRunner {
54
55 /**
56 * Thread pool for asynchronous execution.
57 */
58 private final transient ExecutorService executor =
59 Executors.newFixedThreadPool(
60 Runtime.getRuntime().availableProcessors(),
61 new NamedThreads(
62 "async",
63 "Asynchronous method execution"
64 )
65 );
66
67 /**
68 * Execute method asynchronously.
69 *
70 * <p>This aspect should be used only on {@code void} or
71 * {@link java.util.concurrent.Future} returning methods.
72 *
73 * <p>Try NOT to change the signature of this method, in order to keep
74 * it backward compatible.
75 *
76 * @param point Joint point
77 * @return The result of call
78 */
79 @Around("execution(@com.jcabi.aspects.Async * * (..))")
80 @SuppressWarnings("PMD.AvoidCatchingThrowable")
81 public Object wrap(final ProceedingJoinPoint point) {
82 final Class<?> returned = MethodSignature.class
83 .cast(point.getSignature()).getMethod().getReturnType();
84 if (!Future.class.isAssignableFrom(returned)
85 && !returned.equals(Void.TYPE)) {
86 // @checkstyle LineLength (3 lines)
87 throw new IllegalStateException(
88 String.format(
89 "%s: Return type is %s, not void or Future, cannot use @Async",
90 Mnemos.toText(point, true, true),
91 returned.getCanonicalName()
92 )
93 );
94 }
95 final Future<?> result = this.executor.submit(
96 // @checkstyle AnonInnerLength (23 lines)
97 new Callable<Object>() {
98 @Override
99 public Object call() throws Exception {
100 Object returned = null;
101 try {
102 final Object result = point.proceed();
103 if (result instanceof Future) {
104 returned = ((Future<?>) result).get();
105 }
106 // @checkstyle IllegalCatch (1 line)
107 } catch (final Throwable ex) {
108 throw new IllegalStateException(
109 String.format(
110 "%s: Exception thrown",
111 Mnemos.toText(point, true, true)
112 ),
113 ex
114 );
115 }
116 return returned;
117 }
118 }
119 );
120 Object res = null;
121 if (Future.class.isAssignableFrom(returned)) {
122 res = result;
123 }
124 return res;
125 }
126
127 }