Skip to content

Commit

Permalink
Priorityjobscheduler (eugenp#3583)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
rockoder authored and pivovarit committed Feb 11, 2018
1 parent f7e41c7 commit d935985
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public JobPriority getJobPriority() {
@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) {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@
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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ public void whenMultiplePriorityJobsQueued_thenHighestPriorityJobIsPicked() {
// 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();
Expand Down

0 comments on commit d935985

Please sign in to comment.