Lesson 7 · Processes, threads, and CPU scheduling

SJF Scheduling: Shortest Job First and SRTF

Run the ready job with the shortest next CPU burst. It gives the lowest average waiting time, but the burst has to be predicted and long jobs can starve.

SJF Scheduling: Shortest Job First and SRTF concept diagramA visual explanation of the layout and operations shown in this lesson.shortest job first: run the smallest burst next, and every later job waits lessSJFshortest firstP4burst 3P1burst 6P3burst 7P2burst 80391624waiting time = when the job startsP4 = 0 P1 = 3 P3 = 9 P2 = 16average = (0 + 3 + 9 + 16) / 4 = 7.00why this order is optimala long job placed first adds itswhole burst to every job behind itso no other order beats this oneSRTF is the preemptive form: re-decide whenever a shorter job arrives
1

What SJF Scheduling Is

  1. When the CPU becomes free, look at every job in the ready queue
  2. Pick the one with the shortest next burst; on a tie, the one that arrived first
  3. Run it to the end of that burst
  4. Repeat with whatever is ready at that moment

Shortest job first scheduling (SJF, also called shortest job next) gives the CPU to the ready process whose next CPU burst is shortest. In its basic form it is non-preemptive: once a job starts, it runs until its burst ends, even if a shorter job arrives meanwhile.

The rule compares the next burst, not the job's total running time or its priority. It is one of the policies in CPU scheduling algorithms; the others trade its low average wait for fairness or response time.

  • Decides only when the CPU becomes free
  • Equal bursts fall back to first come, first served
  • Needs to know, or guess, each burst length
2

Worked Example: Average Wait 7.00

Four jobs arrive at time 0 with bursts P1 = 6, P2 = 8, P3 = 7 and P4 = 3. SJF runs them shortest first: P4 (0 to 3), P1 (3 to 9), P3 (9 to 16), P2 (16 to 24).

Waiting time is the start time here, because every job arrived at 0: 0, 3, 9 and 16, so the average is 28 / 4 = 7.00. Turnaround (finish minus arrival) is 3, 9, 16 and 24, an average of 13.00.

FCFS on the same jobs runs P1, P2, P3, P4 and gives waits 0, 6, 14 and 21: average 10.25, with turnaround 16.25. The work is the same 24 units; only the order changed. On the three-job set in the CPU scheduling lesson (6, 2, 4), SJF gives 2.67 for the same reason.

  • Order P4, P1, P3, P2
  • Average wait 7.00, average turnaround 13.00
  • P2 waits 16 here against 6 under FCFS
3

Why Shortest First Is Optimal

No non-preemptive order of the same jobs has a lower average waiting time. The proof is a swap. Suppose a longer job L runs just before a shorter job S. Swap them: S now starts L units earlier and L starts S units later, so the total wait drops by L − S.

On the FCFS order above, swapping P3 (7) and P4 (3) cuts the total wait from 41 to 37. Any order that is not shortest-first contains such a pair, so it can be improved. Only the sorted order cannot.

The claim is about the average. It says nothing about fairness: the longest job waits more under SJF than under almost any other policy.

  • Swapping a long-then-short pair saves L − S
  • Only shortest-first has no such pair left
  • Best average, not best for every job
Implementation

SJF on four jobs

def average_wait(jobs, shortest_first):
    order = sorted(jobs, key=lambda job: job[1]) if shortest_first else jobs
    clock = total = 0
    for name, burst in order:
        total += clock
        clock += burst
    return total / len(order)


jobs = [("P1", 6), ("P2", 8), ("P3", 7), ("P4", 3)]
print("FCFS average wait %.2f" % average_wait(jobs, False))
print("SJF  average wait %.2f" % average_wait(jobs, True))
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <string>
using namespace std;

struct Job {
    string name;
    int burst;
};

// Non-preemptive SJF: sort by burst, then run each to completion.
double schedule(vector<Job> jobs, bool shortestFirst) {
    if (shortestFirst) {
        sort(jobs.begin(), jobs.end(),
             [](const Job& a, const Job& b) { return a.burst < b.burst; });
    }
    int clock = 0;
    int total = 0;
    for (const Job& job : jobs) {
        total += clock;
        clock += job.burst;
    }
    return (double)total / jobs.size();
}

int main() {
    cout << fixed << setprecision(2);
    vector<Job> jobs = {{"P1", 6}, {"P2", 8}, {"P3", 7}, {"P4", 3}};
    cout << "FCFS average wait " << schedule(jobs, false) << endl;
    cout << "SJF  average wait " << schedule(jobs, true) << endl;
    return 0;
}
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    record Job(String name, int burst) {}

    // Non-preemptive SJF: sort by burst, then run each to completion.
    static double schedule(Job[] jobs, boolean shortestFirst) {
        Job[] order = jobs.clone();
        if (shortestFirst) {
            Arrays.sort(order, Comparator.comparingInt(Job::burst));
        }
        int clock = 0;
        int total = 0;
        for (Job job : order) {
            total += clock;
            clock += job.burst();
        }
        return (double) total / order.length;
    }

    public static void main(String[] args) {
        Job[] jobs = {new Job("P1", 6), new Job("P2", 8),
                      new Job("P3", 7), new Job("P4", 3)};
        System.out.printf("FCFS average wait %.2f%n", schedule(jobs, false));
        System.out.printf("SJF  average wait %.2f%n", schedule(jobs, true));
    }
}
Watch it run

Step through it

Running on P1 = 6, P2 = 8, P3 = 7, P4 = 3, all at t = 0

ready queue: bar = next CPU burstP1ready at 06P2ready at 08P3ready at 07P4ready at 03CPU024 units of work in any order
Step 1

Four jobs, all ready at t = 0

P1 needs 6 units of CPU, P2 8, P3 7 and P4 3. All four are in the ready queue at time 0, so whatever the order, the CPU does 24 units of work. Only the order changes how long each job sits waiting.

Output
1 / 11
4

Preemptive SJF: Shortest Remaining Time First

Shortest remaining time first (SRTF) is the preemptive version. It re-decides whenever a job arrives: if the newcomer's burst is shorter than what the running job still needs, the running job is paused and goes back to the ready queue.

With arrivals spread out the two differ. Take P1 = 8 at t = 0, P2 = 4 at t = 1, P3 = 9 at t = 2, P4 = 5 at t = 3. Non-preemptive SJF must let P1 finish first: waits 0, 7, 15, 9, average 7.75. SRTF pauses P1 at t = 1 for P2, then runs P4, P1 and P3: waits 9, 0, 15, 2, average 6.50.

When every job arrives at the same time, nothing arrives later to trigger a preemption, so SJF and SRTF produce the same schedule. That is why SRTF questions always give arrival times.

SJF vs SRTF
SJFSRTF
Decides whenThe running burst endsA burst ends or a job arrives
Can pause a running jobNoYes, for a shorter remaining time
Average wait, staggered example7.756.50
Context switchesOne per jobMore, one per preemption
Starvation riskYesHigher
  • SRTF compares against the time left, not the original burst
  • Same schedule as SJF when all jobs arrive together
  • Lower average wait, more switches
5

Predicting the Next Burst

The scheduler cannot know how long a process will compute before its next I/O, so it guesses from history with an exponential average: τ(n+1) = α·t(n) + (1 − α)·τ(n), where t(n) is the burst just measured, τ(n) the last guess and α between 0 and 1, often 0.5.

Starting from a guess of 10 with α = 0.5, bursts of 6, 4, 6 and 4 give guesses 8, 6, 6 and 5. If the process then switches to bursts of 13, the next guesses are 5, 9 and 11, so for a while SJF ranks it as a short job when it is not. A larger α reacts faster but follows one-off spikes too.

  • α = 1 trusts only the last burst; α = 0 never updates
  • The guess lags any change in behaviour
  • A wrong guess just makes the order less than optimal
6

Starvation and Where SJF Is Used

If short jobs keep arriving, a long job may never be picked: each time the CPU is free there is something shorter. Aging fixes this by counting waiting time in the job's favour until it eventually wins, the same idea used in priority scheduling. SJF is in fact priority scheduling with the predicted burst as the priority.

Pure SJF suits batch systems where run times are known or estimated by the user. General-purpose systems use its idea indirectly: a multilevel feedback queue keeps jobs with short bursts at high priority, which favours them without needing a forecast.

  • Unbounded wait for long jobs without aging
  • SJF = priority scheduling keyed on burst length
  • Used directly in batch systems, indirectly through feedback queues