Skip to content

Commit d2c8ec4

Browse files
Enhance code readability with comments and formatting
Added comments and improved code formatting for clarity.
1 parent 7373d28 commit d2c8ec4

File tree

1 file changed

+70
-27
lines changed

1 file changed

+70
-27
lines changed

src/main/java/com/thealgorithms/scheduling/Preemptive&NonPreemptiveScheduling.java

Lines changed: 70 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
1-
import java.util.Scanner;
21
import java.util.Arrays;
32
import java.util.Comparator;
3+
import java.util.Scanner;
44

5+
/**
6+
* Implements and compares non-preemptive (SJF) and preemptive (SRTF) CPU
7+
* scheduling algorithms.
8+
*/
59
class SchedulingAlgorithms {
10+
11+
/**
12+
* Represents a process with its attributes for scheduling.
13+
*/
614
static class Process {
715
private int pid;
816
private int priority;
@@ -20,8 +28,10 @@ static class Process {
2028
this.arrivalTime = arrivalTime;
2129
this.burstTime = burstTime;
2230
this.remainingTime = burstTime;
23-
this.responseTime = -1;
31+
this.responseTime = -1; // Initialize response time as not set
2432
}
33+
34+
// --- Getters ---
2535
public int getPid() { return pid; }
2636
public int getPriority() { return priority; }
2737
public int getArrivalTime() { return arrivalTime; }
@@ -32,6 +42,7 @@ static class Process {
3242
public int getTurnaroundTime() { return turnaroundTime; }
3343
public int getResponseTime() { return responseTime; }
3444

45+
// --- Setters ---
3546
public void setRemainingTime(int remainingTime) { this.remainingTime = remainingTime; }
3647
public void setCompletionTime(int completionTime) { this.completionTime = completionTime; }
3748
public void setWaitingTime(int waitingTime) { this.waitingTime = waitingTime; }
@@ -40,6 +51,7 @@ static class Process {
4051
}
4152

4253
public static void main(String[] args) {
54+
// Use try-with-resources to ensure the scanner is closed automatically
4355
try (Scanner sc = new Scanner(System.in)) {
4456
System.out.print("Enter number of processes: ");
4557
int n = sc.nextInt();
@@ -63,19 +75,24 @@ public static void main(String[] args) {
6375
int choice = sc.nextInt();
6476

6577
switch (choice) {
66-
case 1:
67-
nonPreemptive(processes);
68-
break;
69-
case 2:
70-
preemptive(processes);
71-
break;
72-
default:
73-
System.out.println("Invalid choice. Exiting.");
74-
return;
78+
case 1:
79+
nonPreemptive(processes);
80+
break;
81+
case 2:
82+
preemptive(processes);
83+
break;
84+
default:
85+
System.out.println("Invalid choice. Exiting.");
86+
return;
7587
}
7688
}
7789
}
78-
90+
91+
/**
92+
* Executes the Non-Preemptive Shortest Job First (SJF) scheduling
93+
* algorithm. Tie-breaking is done based on priority.
94+
* @param processes Array of processes to be scheduled.
95+
*/
7996
private static void nonPreemptive(Process[] processes) {
8097
int n = processes.length;
8198
int completedProcesses = 0;
@@ -87,13 +104,16 @@ private static void nonPreemptive(Process[] processes) {
87104
int minBurstTime = Integer.MAX_VALUE;
88105
int highestPriority = Integer.MAX_VALUE;
89106

107+
// Find the process with the shortest burst time among arrived processes
90108
for (int i = 0; i < n; i++) {
91109
if (processes[i].getArrivalTime() <= currentTime && !isCompleted[i]) {
92110
if (processes[i].getBurstTime() < minBurstTime) {
93111
minBurstTime = processes[i].getBurstTime();
94112
highestPriority = processes[i].getPriority();
95113
selectedProcessIndex = i;
96-
}
114+
}
115+
// Tie-breaker: if burst times are equal, choose based on
116+
// priority
97117
else if (processes[i].getBurstTime() == minBurstTime) {
98118
if (processes[i].getPriority() < highestPriority) {
99119
highestPriority = processes[i].getPriority();
@@ -105,26 +125,34 @@ else if (processes[i].getBurstTime() == minBurstTime) {
105125

106126
if (selectedProcessIndex != -1) {
107127
Process currentProcess = processes[selectedProcessIndex];
108-
128+
129+
// Set response time if it's the first time the process runs
109130
if (currentProcess.getResponseTime() == -1) {
110-
currentProcess.setResponseTime(currentTime - currentProcess.getArrivalTime());
131+
currentProcess.setResponseTime(currentTime - currentProcess.getArrivalTime());
111132
}
112133

113134
currentProcess.setWaitingTime(currentTime - currentProcess.getArrivalTime());
114135
currentTime += currentProcess.getBurstTime();
115136
currentProcess.setCompletionTime(currentTime);
116-
currentProcess.setTurnaroundTime(currentProcess.getCompletionTime() - currentProcess.getArrivalTime());
117-
137+
currentProcess.setTurnaroundTime(
138+
currentProcess.getCompletionTime() - currentProcess.getArrivalTime());
139+
118140
isCompleted[selectedProcessIndex] = true;
119141
completedProcesses++;
120142
} else {
143+
// If no process is available, increment time
121144
currentTime++;
122145
}
123146
}
124147

125148
printResults(processes, "Non-Preemptive SJF (with Priority) Scheduling");
126149
}
127150

151+
/**
152+
* Executes the Preemptive Shortest Remaining Time First (SRTF) scheduling
153+
* algorithm.
154+
* @param processes Array of processes to be scheduled.
155+
*/
128156
private static void preemptive(Process[] processes) {
129157
int n = processes.length;
130158
int completedProcesses = 0;
@@ -134,6 +162,8 @@ private static void preemptive(Process[] processes) {
134162
int shortestJobIndex = -1;
135163
int minRemainingTime = Integer.MAX_VALUE;
136164

165+
// Find the process with the minimum remaining time among the arrived
166+
// processes
137167
for (int i = 0; i < n; i++) {
138168
if (processes[i].getArrivalTime() <= currentTime && processes[i].getRemainingTime() > 0) {
139169
if (processes[i].getRemainingTime() < minRemainingTime) {
@@ -150,19 +180,25 @@ private static void preemptive(Process[] processes) {
150180

151181
Process currentProcess = processes[shortestJobIndex];
152182

183+
// Set response time when the process gets CPU for the first time
153184
if (currentProcess.getResponseTime() == -1) {
154185
currentProcess.setResponseTime(currentTime - currentProcess.getArrivalTime());
155186
}
156187

188+
// Decrement remaining time and increment current time
157189
currentProcess.setRemainingTime(currentProcess.getRemainingTime() - 1);
158190
currentTime++;
159191

192+
// If a process is completed
160193
if (currentProcess.getRemainingTime() == 0) {
161194
completedProcesses++;
162195
currentProcess.setCompletionTime(currentTime);
163-
currentProcess.setTurnaroundTime(currentProcess.getCompletionTime() - currentProcess.getArrivalTime());
164-
currentProcess.setWaitingTime(currentProcess.getTurnaroundTime() - currentProcess.getBurstTime());
165-
196+
currentProcess.setTurnaroundTime(
197+
currentProcess.getCompletionTime() - currentProcess.getArrivalTime());
198+
currentProcess.setWaitingTime(
199+
currentProcess.getTurnaroundTime() - currentProcess.getBurstTime());
200+
201+
// Ensure waiting time is not negative
166202
if (currentProcess.getWaitingTime() < 0) {
167203
currentProcess.setWaitingTime(0);
168204
}
@@ -172,23 +208,30 @@ private static void preemptive(Process[] processes) {
172208
printResults(processes, "Preemptive SRTF Scheduling");
173209
}
174210

211+
/**
212+
* Prints the scheduling results in a formatted table.
213+
* @param processes Array of completed processes.
214+
* @param title The title of the scheduling algorithm.
215+
*/
175216
private static void printResults(Process[] processes, String title) {
176217
System.out.println("\n" + title);
177-
System.out.printf("%-10s%-10s%-15s%-15s%-17s%-15s%-17s%-15s\n",
178-
"Process", "Priority", "Arrival Time", "Burst Time",
179-
"Completion Time", "Waiting Time", "Turnaround Time", "Response Time");
218+
System.out.printf("%-10s%-10s%-15s%-15s%-17s%-15s%-17s%-15s\n", "Process", "Priority",
219+
"Arrival Time", "Burst Time", "Completion Time", "Waiting Time", "Turnaround Time",
220+
"Response Time");
180221

181-
double totalWT = 0, totalTAT = 0;
222+
double totalWT = 0;
223+
double totalTAT = 0;
182224

225+
// Define a comparator to sort processes by PID for consistent output
183226
Comparator<Process> byPid = (p1, p2) -> Integer.compare(p1.getPid(), p2.getPid());
184227
Arrays.sort(processes, byPid);
185228

186229
for (Process p : processes) {
187230
totalWT += p.getWaitingTime();
188231
totalTAT += p.getTurnaroundTime();
189-
System.out.printf("%-10d%-10d%-15d%-15d%-17d%-15d%-17d%-15d\n",
190-
p.getPid(), p.getPriority(), p.getArrivalTime(), p.getBurstTime(),
191-
p.getCompletionTime(), p.getWaitingTime(), p.getTurnaroundTime(), p.getResponseTime());
232+
System.out.printf("%-10d%-10d%-15d%-15d%-17d%-15d%-17d%-15d\n", p.getPid(),
233+
p.getPriority(), p.getArrivalTime(), p.getBurstTime(), p.getCompletionTime(),
234+
p.getWaitingTime(), p.getTurnaroundTime(), p.getResponseTime());
192235
}
193236

194237
System.out.printf("\nAverage Waiting Time: %.2f\n", totalWT / processes.length);

0 commit comments

Comments
 (0)