1 package org.apache.maven.plugins.invoker;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.LinkedHashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ExecutorService;
27 import java.util.concurrent.Executors;
28 import java.util.stream.Collectors;
29
30 import org.apache.maven.plugins.invoker.model.BuildJob;
31
32
33
34
35
36
37 class JobExecutor
38 {
39 interface ThrowableJobConsumer
40 {
41 void accept( BuildJob t ) throws Throwable;
42 }
43
44 private final List<BuildJob> jobs;
45 private final int threadsCount;
46
47 JobExecutor( List<BuildJob> jobs, int threadsCount )
48 {
49 this.jobs = jobs;
50 this.threadsCount = threadsCount;
51 }
52
53 public void forEach( ThrowableJobConsumer jobConsumer )
54 {
55
56 Map<Integer, List<BuildJob>> groupedJobs = jobs.stream()
57 .sorted( ( j1, j2 ) -> Integer.compare( j2.getOrdinal(), j1.getOrdinal() ) )
58 .collect( Collectors.groupingBy( BuildJob::getOrdinal, LinkedHashMap::new, Collectors.toList() ) );
59
60 ExecutorService executorService = Executors.newFixedThreadPool( threadsCount );
61
62 groupedJobs.forEach( ( key, value ) ->
63 {
64
65 List<Callable<Void>> callableJobs = value.stream().map( buildJob -> (Callable<Void>) () ->
66 {
67 try
68 {
69 jobConsumer.accept( buildJob );
70 }
71 catch ( Throwable e )
72 {
73 buildJob.setResult( BuildJob.Result.ERROR );
74 buildJob.setFailureMessage( String.valueOf( e ) );
75 }
76 return null;
77 } ).collect( Collectors.toList() );
78
79 try
80 {
81 executorService.invokeAll( callableJobs );
82 }
83 catch ( InterruptedException e )
84 {
85 Thread.currentThread().interrupt();
86 throw new RuntimeException( e );
87 }
88 } );
89
90
91 executorService.shutdownNow();
92 }
93 }