Using priority queues to schedule work

I was recently reminded that Java has priority queues as part of its collections framework. A priority queue gets its name from one of its first usages, that of scheduling work in an operating system. It is a partially ordered list, which means that it doesn’t have to sort all the items, but only has to ensure that the least valued object is at the head. Because it doesn’t sort, it is more efficient than using a sorted list, but still allows you to pull the items off the queue in sorted order, least to greatest. And it allows you to add items to the queue as you are pulling them off (in which case the items pulled off may not be in sorted order but only the least value at the time of the poll).If an application is scheduled for work and has a priority where a lesser value means the most desired to be executed, we can add it to the priority queue so that scheduling can take place fairly across applications. A priority of zero will mean that it only competes with other applications with a priority of zero to be executed.To demonstrate, let’s create an Application class. This class has a priority, which will be a value from zero to n and an amount of work, some random number between zero and one hundred. We’ll also give it a name so we can track it.The application has a function block that will allow it to consume CPU resources in time units of 0.1 seconds for a certain amount of time. Each time it does work, it reduces the todo and increases the priority (makes it less likely to be rescheduled). The priority can be confusing since priority zero is most likely to be at the top of the priority queue and most likely to be rescheduled.

#java #software-development #sorting-algorithms #software-engineering #software-architecture #priority queues in java

Priority Queues in Java
1.15 GEEK