-
Notifications
You must be signed in to change notification settings - Fork 5
/
BoundedScheduledThreadPoolExecutor.java
36 lines (33 loc) · 1.16 KB
/
BoundedScheduledThreadPoolExecutor.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
package org.genericsystem.cv.application;
import java.lang.reflect.Field;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class BoundedScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
public BoundedScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler, int queueCapacity) {
super(corePoolSize, handler);
setMaximumPoolSize(corePoolSize);
setKeepAliveTime(0, TimeUnit.MILLISECONDS);
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(queueCapacity) {
@Override
public boolean add(Runnable r) {
boolean added = offer(r);
if (added) {
return added;
} else {
getRejectedExecutionHandler().rejectedExecution(r, null);
return false;
}
}
};
try {
Field workQueueField = ThreadPoolExecutor.class.getDeclaredField("workQueue");
workQueueField.setAccessible(true);
workQueueField.set(this, queue);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}