Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathSJFScheduling.java
More file actions
Latest commit
88 lines (76 loc) · 2.92 KB
/
Copy pathSJFScheduling.java
File metadata and controls
88 lines (76 loc) · 2.92 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
packagecom.thealgorithms.scheduling;
importcom.thealgorithms.devutils.entities.ProcessDetails;
importjava.util.ArrayList;
importjava.util.Collection;
importjava.util.Comparator;
importjava.util.Iterator;
importjava.util.List;
/**
* Shortest Job First (SJF) Scheduling Algorithm:
* Executes processes with the shortest burst time first among the ones that have arrived.
*/
publicclassSJFScheduling {
privatefinalList<ProcessDetails> processes;
privatefinalList<String> schedule;
publicSJFScheduling(finalList<ProcessDetails> processes) {
this.processes = newArrayList<>(processes);
this.schedule = newArrayList<>();
sortProcessesByArrivalTime(this.processes);
}
privatestaticvoidsortProcessesByArrivalTime(List<ProcessDetails> processes) {
processes.sort(Comparator.comparingInt(ProcessDetails::getArrivalTime));
}
/**
* Executes the SJF scheduling algorithm and builds the execution order.
*/
publicvoidscheduleProcesses() {
List<ProcessDetails> ready = newArrayList<>();
intsize = processes.size();
inttime = 0;
intexecuted = 0;
Iterator<ProcessDetails> processIterator = processes.iterator();
// This will track the next process to be checked for arrival time
ProcessDetailsnextProcess = null;
if (processIterator.hasNext()) {
nextProcess = processIterator.next();
}
while (executed < size) {
// Load all processes that have arrived by current time
while (nextProcess != null && nextProcess.getArrivalTime() <= time) {
ready.add(nextProcess);
if (processIterator.hasNext()) {
nextProcess = processIterator.next();
} else {
nextProcess = null;
}
}
ProcessDetailsrunning = findShortestJob(ready);
if (running == null) {
time++;
} else {
time += running.getBurstTime();
schedule.add(running.getProcessId());
ready.remove(running);
executed++;
}
}
}
/**
* Finds the process with the shortest job of all the ready processes (based on a process
* @param readyProcesses an array list of ready processes
* @return returns the process' with the shortest burst time OR NULL if there are no ready
* processes
*/
privateProcessDetailsfindShortestJob(Collection<ProcessDetails> readyProcesses) {
returnreadyProcesses.stream().min(Comparator.comparingInt(ProcessDetails::getBurstTime)).orElse(null);
}
/**
* Returns the computed schedule after calling scheduleProcesses().
*/
publicList<String> getSchedule() {
returnschedule;
}
publicList<ProcessDetails> getProcesses() {
returnList.copyOf(processes);
}
}