Priorityjobscheduler (#3583)
* priority based job execution in java * minor fixes * updated to use java 8 features * fix need for type inference * handle exception * indentation * handling exception generated during terminal of normal flow * handling exception generated during terminal of normal flow * added comment
This commit is contained in:
parent
f7e41c7a17
commit
d935985ec1
|
@ -16,7 +16,8 @@ public class Job implements Runnable {
|
|||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
System.out.println("Job:" + jobName + " Priority:" + jobPriority);
|
||||
System.out.println("Job:" + jobName +
|
||||
" Priority:" + jobPriority);
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
|
|
|
@ -9,21 +9,21 @@ import java.util.concurrent.TimeUnit;
|
|||
public class PriorityJobScheduler {
|
||||
|
||||
private ExecutorService priorityJobPoolExecutor;
|
||||
private ExecutorService priorityJobScheduler;
|
||||
private PriorityBlockingQueue<Runnable> priorityQueue;
|
||||
private ExecutorService priorityJobScheduler =
|
||||
Executors.newSingleThreadExecutor();
|
||||
private PriorityBlockingQueue<Job> priorityQueue;
|
||||
|
||||
public PriorityJobScheduler(Integer poolSize, Integer queueSize) {
|
||||
priorityJobPoolExecutor = Executors.newFixedThreadPool(poolSize);
|
||||
Comparator<? super Job> jobComparator = Comparator.comparing(Job::getJobPriority);
|
||||
priorityQueue = new PriorityBlockingQueue<Runnable>(queueSize,
|
||||
(Comparator<? super Runnable>) jobComparator);
|
||||
priorityQueue = new PriorityBlockingQueue<Job>(queueSize,
|
||||
Comparator.comparing(Job::getJobPriority));
|
||||
|
||||
priorityJobScheduler = Executors.newSingleThreadExecutor();
|
||||
priorityJobScheduler.execute(()->{
|
||||
while (true) {
|
||||
try {
|
||||
priorityJobPoolExecutor.execute(priorityQueue.take());
|
||||
} catch (InterruptedException e) {
|
||||
// exception needs special handling
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -30,7 +30,9 @@ public class PriorityJobSchedulerUnitTest {
|
|||
// delay to avoid job sleep (added for demo) being interrupted
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException ignored) {
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
pjs.closeScheduler();
|
||||
|
|
Loading…
Reference in New Issue