-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWorkQueue.java
More file actions
68 lines (58 loc) · 1.42 KB
/
WorkQueue.java
File metadata and controls
68 lines (58 loc) · 1.42 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
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class WorkQueue {
private static final int numThreads = 10;
private static WorkQueue instance = null;
private final ThreadPoolExecutor workers;
/**
* Dummy object used to send messages from queue to main
*/
public static Object messenger = new Object();
private WorkQueue() {
workers = new ThreadPoolExecutor(numThreads, numThreads, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
public static WorkQueue getInstance() {
if (instance == null) {
synchronized (WorkQueue.class) {
if (instance == null) {
instance = new WorkQueue();
}
}
}
return instance;
}
public void execute(Runnable r) {
workers.execute(r);
}
public void shutdown() {
workers.shutdown();
// notify the main thread when work queue is shutting down
synchronized (messenger) {
messenger.notifyAll();
}
}
public boolean isShutdown() {
return workers.isShutdown();
}
public int getActiveCount() {
return workers.getActiveCount();
}
public long getTaskCount() {
return workers.getTaskCount();
}
/**
* Blocks until work queue is shutdown
*/
public void awaitShutdown() {
while (!workers.isShutdown()) {
synchronized (messenger) {
try {
messenger.wait();
} catch (InterruptedException e) {
}
}
Thread.yield();
}
}
}