-
Notifications
You must be signed in to change notification settings - Fork 613
/
BlockingTaskAwareExecutorServiceImpl.java
223 lines (193 loc) · 6.82 KB
/
BlockingTaskAwareExecutorServiceImpl.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package org.infinispan.util.concurrent;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.infinispan.commons.time.TimeService;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* A special executor service that accepts a {@code BlockingRunnable}. This special runnable gives hints about the code
* to be running in order to avoiding put a runnable that will block the thread. In this way, only when the runnable
* says that is ready, it is sent to the real executor service
*
* @author Pedro Ruivo
* @since 5.3
*/
public class BlockingTaskAwareExecutorServiceImpl extends AbstractExecutorService implements BlockingTaskAwareExecutorService {
private static final Log log = LogFactory.getLog(BlockingTaskAwareExecutorServiceImpl.class);
private static final boolean trace = log.isTraceEnabled();
private final Queue<BlockingRunnable> blockedTasks;
private final ExecutorService executorService;
private final TimeService timeService;
private final ControllerThread controllerThread;
private volatile boolean shutdown;
public BlockingTaskAwareExecutorServiceImpl(String controllerThreadName, ExecutorService executorService, TimeService timeService) {
this.blockedTasks = new ConcurrentLinkedQueue<>();
this.executorService = executorService;
this.timeService = timeService;
this.shutdown = false;
this.controllerThread = new ControllerThread(controllerThreadName);
controllerThread.start();
}
@Override
public final void execute(BlockingRunnable runnable) {
if (shutdown) {
throw new RejectedExecutionException("Executor Service is already shutdown");
}
if (runnable.isReady()) {
doExecute(runnable);
if (trace) {
log.tracef("Added a new task directly: %d task(s) are waiting", blockedTasks.size());
}
} else {
//we no longer submit directly to the executor service.
blockedTasks.offer(runnable);
controllerThread.checkForReadyTask();
if (trace) {
log.tracef("Added a new task to the queue: %d task(s) are waiting", blockedTasks.size());
}
}
}
@Override
public void shutdown() {
shutdown = true;
controllerThread.interrupt();
executorService.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
shutdown = true;
controllerThread.interrupt();
List<Runnable> runnableList = new LinkedList<>();
runnableList.addAll(executorService.shutdownNow());
runnableList.addAll(blockedTasks);
return runnableList;
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
return shutdown && blockedTasks.isEmpty() && executorService.isTerminated();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
final long endTime = timeService.expectedEndTime(timeout, unit);
long waitTime = timeService.remainingTime(endTime, TimeUnit.MILLISECONDS);
while (!blockedTasks.isEmpty() && waitTime > 0) {
Thread.sleep(waitTime);
waitTime = timeService.remainingTime(endTime, TimeUnit.MILLISECONDS);
}
return isTerminated();
}
@Override
public final void checkForReadyTasks() {
controllerThread.checkForReadyTask();
}
@Override
public void execute(Runnable command) {
if (shutdown) {
throw new RejectedExecutionException("Executor Service is already shutdown");
}
if (command instanceof BlockingRunnable) {
execute((BlockingRunnable) command);
} else {
execute(new RunnableWrapper(command));
}
}
public ExecutorService getExecutorService() {
return executorService;
}
private void doExecute(BlockingRunnable runnable) {
try {
executorService.execute(runnable);
} catch (RejectedExecutionException rejected) {
//put it back!
blockedTasks.offer(runnable);
checkForReadyTasks();
}
}
private class ControllerThread extends Thread {
private final Semaphore semaphore;
private volatile boolean interrupted;
public ControllerThread(String controllerThreadName) {
super(controllerThreadName);
this.setUncaughtExceptionHandler((t, e) -> log.errorf(e, "Exception in thread %s", t.getName()));
semaphore = new Semaphore(0);
}
public void checkForReadyTask() {
semaphore.release();
}
@Override
public void interrupt() {
interrupted = true;
super.interrupt();
semaphore.release();
}
@Override
public void run() {
while (!interrupted) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
return;
}
semaphore.drainPermits();
int size = blockedTasks.size();
if (size == 0) {
continue;
}
ArrayDeque<BlockingRunnable> readyList = new ArrayDeque<>(size);
for (Iterator<BlockingRunnable> iterator = blockedTasks.iterator(); iterator.hasNext(); ) {
BlockingRunnable runnable = iterator.next();
boolean ready;
try {
ready = runnable.isReady();
} catch (Exception e) {
log.debugf(e, "Failed to check ready state of %s, dropping.", runnable);
iterator.remove();
continue;
}
if (ready) {
iterator.remove();
readyList.addLast(runnable);
}
}
if (trace) {
log.tracef("Tasks to be executed=%s, still pending=~%s", readyList.size(), size);
}
BlockingRunnable runnable;
while ((runnable = readyList.pollFirst()) != null) {
doExecute(runnable);
}
}
}
}
private static class RunnableWrapper implements BlockingRunnable {
private final Runnable runnable;
private RunnableWrapper(Runnable runnable) {
this.runnable = runnable;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void run() {
runnable.run();
}
@Override
public String toString() {
return "RunnableWrapper(" + runnable + ")";
}
}
}