forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSJFScheduling.java
More file actions
88 lines (76 loc) · 2.92 KB
/
SJFScheduling.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
package com.thealgorithms.scheduling;
import com.thealgorithms.devutils.entities.ProcessDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* Shortest Job First (SJF) Scheduling Algorithm:
* Executes processes with the shortest burst time first among the ones that have arrived.
*/
public class SJFScheduling {
private final List<ProcessDetails> processes;
private final List<String> schedule;
public SJFScheduling(final List<ProcessDetails> processes) {
this.processes = new ArrayList<>(processes);
this.schedule = new ArrayList<>();
sortProcessesByArrivalTime(this.processes);
}
private static void sortProcessesByArrivalTime(List<ProcessDetails> processes) {
processes.sort(Comparator.comparingInt(ProcessDetails::getArrivalTime));
}
/**
* Executes the SJF scheduling algorithm and builds the execution order.
*/
public void scheduleProcesses() {
List<ProcessDetails> ready = new ArrayList<>();
int size = processes.size();
int time = 0;
int executed = 0;
Iterator<ProcessDetails> processIterator = processes.iterator();
// This will track the next process to be checked for arrival time
ProcessDetails nextProcess = 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;
}
}
ProcessDetails running = 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
*/
private ProcessDetails findShortestJob(Collection<ProcessDetails> readyProcesses) {
return readyProcesses.stream().min(Comparator.comparingInt(ProcessDetails::getBurstTime)).orElse(null);
}
/**
* Returns the computed schedule after calling scheduleProcesses().
*/
public List<String> getSchedule() {
return schedule;
}
public List<ProcessDetails> getProcesses() {
return List.copyOf(processes);
}
}