blob: 054e84c62f73d551141fd1f85308da8ebce291b9 (
plain) (
blame)
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
|
package org.openslx.bwlp.sat.maintenance;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Maintenance extends Thread {
private static final Logger LOGGER = LogManager.getLogger(Maintenance.class);
private static Set<Maintenance> workers = new HashSet<>();
private static BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(50);
private static final AtomicInteger ID_CTR = new AtomicInteger();
private Maintenance() {
super("Maint-" + ID_CTR.incrementAndGet());
setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2);
}
private synchronized static void ensureRunning() {
if (workers.isEmpty() || (queue.size() > 5 && workers.size() < 3)) {
Maintenance worker = new Maintenance();
worker.start();
workers.add(worker);
}
}
public static void submit(Runnable job) throws InterruptedException {
ensureRunning();
queue.put(job);
}
public static boolean trySubmit(Runnable job) {
ensureRunning();
return queue.offer(job);
}
@Override
public void run() {
LOGGER.info("Maintenance Thread started");
try {
for (;;) {
Runnable job = queue.take();
runJob(job);
}
} catch (InterruptedException e) {
LOGGER.warn("Maintenance Thread was interrupted!", e);
Thread.currentThread().interrupt();
}
}
private void runJob(Runnable job) {
try {
job.run();
} catch (Throwable t) {
LOGGER.warn("Uncaught exception in job '" + job.getClass().getSimpleName() + "'", t);
}
}
}
|