1 package org.apache.maven.surefire.junitcore.pc;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.Collection;
23 import java.util.concurrent.ExecutorService;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.ThreadPoolExecutor;
26 import java.util.concurrent.atomic.AtomicBoolean;
27
28
29
30
31
32
33
34
35
36
37
38
39
40 abstract class AbstractThreadPoolStrategy extends SchedulingStrategy {
41 private final ExecutorService threadPool;
42 private final Collection<Future<?>> futureResults;
43 private final AtomicBoolean canSchedule = new AtomicBoolean(true);
44
45 AbstractThreadPoolStrategy(ExecutorService threadPool) {
46 this(threadPool, null);
47 }
48
49 AbstractThreadPoolStrategy(ExecutorService threadPool, Collection<Future<?>> futureResults) {
50 this.threadPool = threadPool;
51 this.futureResults = futureResults;
52 }
53
54 protected final ExecutorService getThreadPool() {
55 return threadPool;
56 }
57
58 protected final Collection<Future<?>> getFutureResults() {
59 return futureResults;
60 }
61
62 protected final void disable() {
63 canSchedule.set(false);
64 }
65
66 @Override
67 public void schedule(Runnable task) {
68 if (canSchedule()) {
69 Future<?> futureResult = threadPool.submit(task);
70 if (futureResults != null) {
71 futureResults.add(futureResult);
72 }
73 }
74 }
75
76 @Override
77 protected boolean stop() {
78 boolean wasRunning = canSchedule.getAndSet(false);
79 if (threadPool.isShutdown()) {
80 wasRunning = false;
81 } else {
82 threadPool.shutdown();
83 }
84 return wasRunning;
85 }
86
87 @Override
88 protected boolean stopNow() {
89 boolean wasRunning = canSchedule.getAndSet(false);
90 if (threadPool.isShutdown()) {
91 wasRunning = false;
92 } else {
93 threadPool.shutdownNow();
94 }
95 return wasRunning;
96 }
97
98 @Override
99 protected void setDefaultShutdownHandler(Scheduler.ShutdownHandler handler) {
100 if (threadPool instanceof ThreadPoolExecutor) {
101 ThreadPoolExecutor pool = (ThreadPoolExecutor) threadPool;
102 handler.setRejectedExecutionHandler(pool.getRejectedExecutionHandler());
103 pool.setRejectedExecutionHandler(handler);
104 }
105 }
106
107 @Override
108 public final boolean canSchedule() {
109 return canSchedule.get();
110 }
111 }