-
Notifications
You must be signed in to change notification settings - Fork 25
/
BoundedExecutor.java
41 lines (36 loc) · 981 Bytes
/
BoundedExecutor.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
package net.jcip.examples;
import java.util.concurrent.*;
import net.jcip.annotations.*;
/**
* BoundedExecutor
* <p/>
* Using a Semaphore to throttle task submission
*
* @author Brian Goetz and Tim Peierls
*/
@ThreadSafe
public class BoundedExecutor {
private final Executor exec;
private final Semaphore semaphore;
public BoundedExecutor(Executor exec, int bound) {
this.exec = exec;
this.semaphore = new Semaphore(bound);
}
public void submitTask(final Runnable command)
throws InterruptedException {
semaphore.acquire();
try {
exec.execute(new Runnable() {
public void run() {
try {
command.run();
} finally {
semaphore.release();
}
}
});
} catch (RejectedExecutionException e) {
semaphore.release();
}
}
}