forked from mlohbihler/various
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderedExecutorService.java
More file actions
83 lines (72 loc) · 2.85 KB
/
OrderedExecutorService.java
File metadata and controls
83 lines (72 loc) · 2.85 KB
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
package lohbihler.warp;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author Terry Packer
*/
public class OrderedExecutorService extends ThreadPoolExecutor {
/**
* Lock held on access to workers set and related bookkeeping. While we could use a concurrent
* set of some sort, it turns out to be generally preferable to use a lock. Among the reasons is
* that this serializes interruptIdleWorkers, which avoids unnecessary interrupt storms,
* especially during shutdown. Otherwise exiting threads would concurrently interrupt those that
* have not yet interrupted. It also simplifies some of the associated statistics bookkeeping of
* largestPoolSize etc. We also hold mainLock on shutdown and shutdownNow, for the sake of
* ensuring workers set is stable while separately checking permission to interrupt and actually
* interrupting.
*/
private final ReentrantReadWriteLock mainLock = new ReentrantReadWriteLock();
private OrderedRunnable first;
public OrderedExecutorService(int corePoolSize, int maximumPoolSize, long keepAliveTime,
TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
public void execute(Runnable command) {
ReentrantReadWriteLock lock = mainLock;
lock.writeLock().lock();
try {
if (first == null) {
first = new OrderedRunnable(null, command);
} else {
first = new OrderedRunnable(first, command);
}
} finally {
lock.writeLock().unlock();
}
super.execute(first);
}
private class OrderedRunnable implements Runnable {
private final OrderedRunnable previous;
private volatile CountDownLatch latch;
private final Runnable command;
private volatile boolean success = false;
private volatile boolean done = false;
public OrderedRunnable(OrderedRunnable previous, Runnable command) {
this.previous = previous;
this.command = command;
this.latch = new CountDownLatch(1);
}
public void await() throws InterruptedException {
latch.await();
}
@Override
public void run() {
try {
command.run();
success = true;
if (previous != null) {
previous.await();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
done = true;
latch.countDown();
}
}
}
}