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:
Ganesh 2018-02-11 13:29:30 +05:30 committed by Grzegorz Piwowarek
parent f7e41c7a17
commit d935985ec1
3 changed files with 11 additions and 8 deletions

View File

@ -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) {
}

View File

@ -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;
}
}

View File

@ -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();