forked from ScottOaks/JavaPerformanceTuning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPausingThreadPoolExecutor.java
More file actions
77 lines (67 loc) · 1.92 KB
/
Copy pathPausingThreadPoolExecutor.java
File metadata and controls
77 lines (67 loc) · 1.92 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
/*
* Copyright (c) 2013,2014 Scott Oaks. All rights reserved.
*/
package net.sdo;
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.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class PausingThreadPoolExecutor extends ThreadPoolExecutor {
private boolean isPaused;
private ReentrantLock pauseLock = new ReentrantLock();
private Condition unpaused = pauseLock.newCondition();
private CountDownLatch latch;
private BlockingQueue<Runnable> queue;
private int latchCount;
public PausingThreadPoolExecutor(int nThreads, BlockingQueue<Runnable> queue) {
super(nThreads, nThreads, Long.MAX_VALUE, TimeUnit.DAYS, queue);
this.queue = queue;
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
pauseLock.lock();
try {
while (isPaused) {
unpaused.await();
}
} catch (InterruptedException ie) {
t.interrupt();
} finally {
pauseLock.unlock();
}
}
public void addTask(Runnable r) {
latchCount++;
queue.add(r);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
latch.countDown();
}
public void pause() {
pauseLock.lock();
try {
isPaused = true;
} finally {
pauseLock.unlock();
}
}
public void resume() {
pauseLock.lock();
latch = new CountDownLatch(latchCount);
latchCount = 0;
try {
isPaused = false;
unpaused.signalAll();
} finally {
pauseLock.unlock();
}
try {
latch.await();
} catch (InterruptedException ex) {
}
}
}