- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathAgingScheduling.java
62 lines (54 loc) · 1.59 KB
/
AgingScheduling.java
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
packagecom.thealgorithms.scheduling;
importjava.util.LinkedList;
importjava.util.Queue;
/**
* AgingScheduling is an algorithm designed to prevent starvation
* by gradually increasing the priority of waiting tasks.
* The longer a process waits, the higher its priority becomes.
*
* Use Case: Useful in systems with mixed workloads to avoid
* lower-priority tasks being starved by higher-priority tasks.
*
* @author Hardvan
*/
publicfinalclassAgingScheduling {
staticclassTask {
Stringname;
intwaitTime;
intpriority;
Task(Stringname, intpriority) {
this.name = name;
this.priority = priority;
this.waitTime = 0;
}
}
privatefinalQueue<Task> taskQueue;
publicAgingScheduling() {
taskQueue = newLinkedList<>();
}
/**
* Adds a task to the scheduler with a given priority.
*
* @param name name of the task
* @param priority priority of the task
*/
publicvoidaddTask(Stringname, intpriority) {
taskQueue.offer(newTask(name, priority));
}
/**
* Schedules the next task based on the priority and wait time.
* The priority of a task increases with the time it spends waiting.
*
* @return name of the next task to be executed
*/
publicStringscheduleNext() {
if (taskQueue.isEmpty()) {
returnnull;
}
TasknextTask = taskQueue.poll();
nextTask.waitTime++;
nextTask.priority += nextTask.waitTime;
taskQueue.offer(nextTask);
returnnextTask.name;
}
}