Debian Codegraph @

src/main/java/com/jcabi/aspects/aj/Parallelizer.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 com.jcabi.aspects.Immutable;
33 import com.jcabi.aspects.Parallel;
34 import com.jcabi.log.VerboseThreads;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.LinkedList;
38 import java.util.List;
39 import java.util.concurrent.Callable;
40 import java.util.concurrent.CountDownLatch;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.ExecutorService;
43 import java.util.concurrent.Executors;
44 import java.util.concurrent.Future;
45 import org.aspectj.lang.ProceedingJoinPoint;
46 import org.aspectj.lang.annotation.Around;
47 import org.aspectj.lang.annotation.Aspect;
48 import org.aspectj.lang.reflect.MethodSignature;
49
50 /**
51 * Execute method in multiple threads.
52 *
53 * @author Krzysztof Krason ([email protected])
54 * @version $Id: 7d11b15cb6b86fe9c2006e274e76f6dfaf6a39d2 $
55 * @since 0.10
56 * @see com.jcabi.aspects.Parallel
57 */
58 @Aspect
59 @Immutable
60 public final class Parallelizer {
61
62 /**
63 * Execute method in multiple threads.
64 *
65 * <p>This aspect should be used only on void returning methods.
66 *
67 * <p>Try NOT to change the signature of this method, in order to keep
68 * it backward compatible.
69 *
70 * @param point Joint point
71 * @return The result of call
72 * @throws ParallelException If something goes wrong inside
73 * @checkstyle IllegalThrowsCheck (4 lines)
74 */
75 @Around("execution(@com.jcabi.aspects.Parallel * * (..))")
76 public Object wrap(final ProceedingJoinPoint point)
77 throws ParallelException {
78 final int total = ((MethodSignature) point.getSignature())
79 .getMethod().getAnnotation(Parallel.class).threads();
80 final Collection<Callable<Throwable>> callables =
81 new ArrayList<Callable<Throwable>>(total);
82 final CountDownLatch start = new CountDownLatch(1);
83 for (int thread = 0; thread < total; ++thread) {
84 callables.add(this.callable(point, start));
85 }
86 final ExecutorService executor = Executors
87 .newFixedThreadPool(total, new VerboseThreads());
88 final List<Future<Throwable>> futures =
89 new ArrayList<Future<Throwable>>(total);
90 for (final Callable<Throwable> callable : callables) {
91 futures.add(executor.submit(callable));
92 }
93 start.countDown();
94 final Collection<Throwable> failures = new LinkedList<Throwable>();
95 for (final Future<Throwable> future : futures) {
96 this.process(failures, future);
97 }
98 executor.shutdown();
99 if (!failures.isEmpty()) {
100 throw this.exceptions(failures);
101 }
102 return null;
103 }
104
105 /**
106 * Process futures.
107 * @param failures Collection of failures.
108 * @param future Future tu process.
109 */
110 private void process(final Collection<Throwable> failures,
111 final Future<Throwable> future) {
112 final Throwable exception;
113 try {
114 exception = future.get();
115 if (exception != null) {
116 failures.add(exception);
117 }
118 } catch (final InterruptedException ex) {
119 failures.add(ex);
120 } catch (final ExecutionException ex) {
121 failures.add(ex);
122 }
123 }
124
125 /**
126 * Create parallel exception.
127 * @param failures List of exceptions from threads.
128 * @return Aggregated exceptions.
129 */
130 @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
131 private ParallelException exceptions(
132 final Collection<Throwable> failures) {
133 ParallelException current = null;
134 for (final Throwable failure : failures) {
135 current = new ParallelException(failure, current);
136 }
137 return current;
138 }
139
140 /**
141 * Create callable that executes join point.
142 * @param point Join point to use.
143 * @param start Latch to use.
144 * @return Created callable.
145 */
146 @SuppressWarnings("PMD.AvoidCatchingThrowable")
147 private Callable<Throwable> callable(final ProceedingJoinPoint point,
148 final CountDownLatch start) {
149 return new Callable<Throwable>() {
150 @Override
151 public Throwable call() {
152 Throwable result = null;
153 try {
154 start.await();
155 point.proceed();
156 // @checkstyle IllegalCatchCheck (1 line)
157 } catch (final Throwable ex) {
158 result = ex;
159 }
160 return result;
161 }
162 };
163 }
164
165 /**
166 * Exception that encapsulates all exceptions thrown from threads.
167 */
168 private static final class ParallelException extends Exception {
169 /**
170 * Serialization marker.
171 */
172 private static final long serialVersionUID = 0x8743ef363febc422L;
173 /**
174 * Next parallel exception.
175 */
176 private final transient ParallelException next;
177 /**
178 * Constructor.
179 * @param cause Cause of the current exception.
180 * @param nxt Following exception.
181 */
182 protected ParallelException(final Throwable cause,
183 final ParallelException nxt) {
184 super(cause);
185 this.next = nxt;
186 }
187 /**
188 * Get next parallel exception.
189 * @return Next exception.
190 */
191 public ParallelException getNext() {
192 return this.next;
193 }
194 }
195
196 }