1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class ParallelNoResult { public <T> T getParallelResult(List<Node<T>> nodes) throws Exception { final ExecutorService exec = Executors.newCachedThreadPool(); final AtomicInteger countTask = new AtomicInteger(0);
ValueLatch<T> result = new ValueLatch<>(); parallelRecursive(exec, nodes, result, countTask);
exec.shutdown(); exec.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
return result.getValue(); }
public <T> void parallelRecursive(final Executor exec, List<Node<T>> nodes, final ValueLatch<T> valueLatch, final AtomicInteger countTask) { for (Node<T> node : nodes) { exec.execute(() -> { try { countTask.incrementAndGet(); T result = node.compute(); if (result != null) { valueLatch.setValue(result); } } finally { if (countTask.decrementAndGet() == 0) { valueLatch.setValue(null); } } }); parallelRecursive(exec, node.getChildren(), valueLatch, countTask); } }
}
|