- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathAsyncJobMonitor.java
More file actions
Latest commit
85 lines (72 loc) · 2.38 KB
/
Copy pathAsyncJobMonitor.java
File metadata and controls
85 lines (72 loc) · 2.38 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
78
79
80
81
82
83
84
85
/**
*
*/
importjava.util.Map;
importjava.util.Queue;
importjava.util.concurrent.ConcurrentLinkedQueue;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.ConcurrentHashMap;
importjava.util.concurrent.Executors;
importjava.util.concurrent.TimeUnit;
publicclassAsyncJobMonitor {
privatestaticfinallongINIT_TIME = System.currentTimeMillis();
privateQueue<Job> queue = newConcurrentLinkedQueue<>();
privateMap<String, Long> endMap = newConcurrentHashMap<>();
publicvoidstart(Jobjob) {
queue.add(job);
}
publicvoidend(Stringid, longend) {
endMap.put(id, end);
cleanQueue();
}
privatevoidcleanQueue() {
while (!queue.isEmpty() && endMap.containsKey(queue.peek().id)) {
Jobcurr = queue.poll();
curr.end = endMap.get(curr.id);
endMap.remove(curr.id);
printJob(curr);
}
}
privatevoidprintJob(Jobjob) {
System.out.println(String.format("now: %s, job: %s, start: %s, end: %s",
System.currentTimeMillis() - INIT_TIME,
job.id,
job.start - INIT_TIME,
job.end - INIT_TIME));
}
staticclassJob {
Stringid;
longstart;
longend;
Job(Stringid, longstart) {
this.id = id;
this.start = start;
}
}
publicstaticvoidmain(String[] args) {
AsyncJobMonitormonitor = newAsyncJobMonitor();
ExecutorServiceexecutorService = Executors.newFixedThreadPool(5);
String[] ids = newString[]{"a", "b", "c", "d", "e"};
long[] times = newlong[]{5, 2, 5, 4, 1};
for (inti=0; i<5; i++) {
Stringid = ids[i];
longtime = times[i];
executorService.execute(() -> {
Jobjob = newJob(id, System.currentTimeMillis());
monitor.start(job);
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedExceptionex) {
ex.printStackTrace();
}
monitor.end(id, System.currentTimeMillis());
});
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedExceptionex) {
ex.printStackTrace();
}
}
executorService.shutdown();
}
}