-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimeoutPool.java
107 lines (98 loc) · 3.71 KB
/
TimeoutPool.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
import com.google.common.collect.HashMultimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created with IntelliJ IDEA.
* User: WuYifei
* Date: 2017/2/8
* Time: 10:13
*/
public abstract class TimeoutPool<T extends TimeoutJob> {
protected boolean start = false;
protected ReentrantLock lock;
protected Logger logger = LoggerFactory.getLogger(getClass());
//bind t to currentThread,may be remove by timeout thread,ThreadLocal cannot be used
protected HashMultimap<T, Thread> threadMap = HashMultimap.create();
public boolean add(T t) {
lock.lock();
try {
return threadMap.put(t, Thread.currentThread());
} finally {
lock.unlock();
}
}
public boolean remove(T t) {
lock.lock();
try {
return threadMap.remove(t, Thread.currentThread());
} finally {
lock.unlock();
}
}
public void start() {
start(defaults);
}
public synchronized void start(DoTimeout doTimeout) {
if (!start) {
start = true;
lock = new ReentrantLock();
final Thread thread = new Thread(doTimeout, "timeout-pool-thread-" + getClass().getSimpleName());
thread.start();
ThreadPoolUtil.registerShutdown(thread);
}
}
protected static interface DoTimeout extends Runnable {
}
protected DoTimeout defaults = new DoTimeout() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.debug(e.getMessage(), e);
}
final HashMultimap<TimeoutJob, Thread> timeoutJobs = HashMultimap.create();
lock.lock();
try {
Iterator<Map.Entry<T, Thread>> iterator = threadMap.entries().iterator();
while (iterator.hasNext()) {
Map.Entry<T, Thread> entry = iterator.next();
T job = entry.getKey();
if (job.checkTimeout()) {
iterator.remove();
timeoutJobs.put(job, entry.getValue());
}
}
} finally {
lock.unlock();
}
if (!executor.isShutdown()) {
executor.execute(new Runnable() {
public void run() {
for (Map.Entry<TimeoutJob, Thread> entry : timeoutJobs.entries()) {
try {
entry.getKey().about(entry.getValue());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
});
} else {
for (Map.Entry<TimeoutJob, Thread> entry : timeoutJobs.entries()) {
try {
entry.getKey().about(entry.getValue());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
}
}
};
protected ExecutorService executor = ThreadPoolUtil.newFixedExecutor(2, "job-clean");
}