Skip to lesson

CPU scheduling: FCFS and SJF

A placement paper gives you four or five processes and asks for the average waiting time under FCFS and SJF. The examiner is checking your Gantt chart and three formulas, because one wrong cell spoils the whole average.

Terms: arrival, burst, waiting, turnaround and response time

Waiting time is the time a process spends in the ready queue without running; it equals turnaround time minus burst time.

The program below takes one process (arrives at 2, needs 5 ms, first runs at 6, finishes at 14) and applies the three formulas to it.

Example 1 · The three formulas for one process

TimesDemo.javaJava
public class TimesDemo {    public static void main(String[] args) {        int arrival = 2, burst = 5, firstRun = 6, completion = 14;
        int turnaround = completion - arrival;        int waiting = turnaround - burst;        int response = firstRun - arrival;
        System.out.println("Turnaround = " + completion + " - " + arrival + " = " + turnaround);        System.out.println("Waiting    = " + turnaround + " - " + burst + " = " + waiting);        System.out.println("Response   = " + firstRun + " - " + arrival + " = " + response);    }}
Output
Turnaround = 14 - 2 = 12
Waiting    = 12 - 5 = 7
Response   = 6 - 2 = 4

What this code does

  • The process was in the system for 12 ms but ran for only 5, so it waited 7 ms in total.
  • Response time (4) is smaller than waiting time (7) because the process was preempted after it started and waited again later.

Arrival time is when a process enters the ready queue, burst time is the CPU time it needs and completion time is when it finishes. From these: turnaround time (TAT) = completion − arrival, the total time in the system; waiting time = turnaround − burst; response time = first run − arrival, how long before it starts at all.

Write the three formulas at the top of your rough sheet before you start: every numerical uses them. Revise: Processes and threads (opens in a new tab)

FCFS with a Gantt chart and the convoy effect

Convoy effect is a queue of short processes stuck behind one long process, which raises the average waiting time sharply.

The program below runs FCFS on four processes and prints each start, finish, turnaround and waiting time, the Gantt chart and the averages. A second program then shows the convoy effect.

Example 2 · FCFS simulator with a Gantt chart

FcfsDemo.javaJava
import java.util.List;
record Proc(String name, int arrival, int burst) {}
public class FcfsDemo {    public static void main(String[] args) {        List<Proc> ps = List.of(new Proc("P1", 0, 8), new Proc("P2", 1, 4),                new Proc("P3", 2, 9), new Proc("P4", 3, 5));   // sorted by arrival        int time = 0, totalWait = 0, totalTat = 0;        StringBuilder gantt = new StringBuilder("0");        for (Proc p : ps) {            time = Math.max(time, p.arrival());   // CPU may be idle until arrival            int start = time;            time += p.burst();            int tat = time - p.arrival();            int wait = tat - p.burst();            totalTat += tat;            totalWait += wait;            gantt.append(" [").append(p.name()).append("] ").append(time);            System.out.println(p.name() + ": start " + start + ", finish " + time + ", TAT " + tat + ", WT " + wait);        }        System.out.println("Gantt: " + gantt);        System.out.printf("Average WT = %.2f, average TAT = %.2f%n", totalWait / 4.0, totalTat / 4.0);    }}
Output
P1: start 0, finish 8, TAT 8, WT 0
P2: start 8, finish 12, TAT 11, WT 7
P3: start 12, finish 21, TAT 19, WT 10
P4: start 21, finish 26, TAT 23, WT 18
Gantt: 0 [P1] 8 [P2] 12 [P3] 21 [P4] 26
Average WT = 8.75, average TAT = 15.25

What this code does

  • Math.max(time, p.arrival()) handles a gap: if the next process has not arrived yet, the CPU sits idle until it does.
  • Average waiting is 35 ÷ 4 = 8.75. P4 waits 18 ms for a 5 ms job because of the long jobs ahead of it.

Example 3 · The convoy effect in numbers

ConvoyDemo.javaJava
public class ConvoyDemo {    static double averageWait(int[] bursts) {          // all arrive at time 0        int time = 0, totalWait = 0;        for (int b : bursts) {            totalWait += time;            time += b;        }        return (double) totalWait / bursts.length;    }
    public static void main(String[] args) {        System.out.println("Long job first  (24, 3, 3): avg WT = " + averageWait(new int[] {24, 3, 3}));        System.out.println("Short jobs first (3, 3, 24): avg WT = " + averageWait(new int[] {3, 3, 24}));    }}
Output
Long job first  (24, 3, 3): avg WT = 17.0
Short jobs first (3, 3, 24): avg WT = 3.0

What this code does

  • Same three jobs, same total work. Only the order changed, and the average wait fell from 17 to 3.
  • This is why FCFS is weak when one long job arrives first, and why SJF exists.

First-come, first-served (FCFS) runs processes in order of arrival, each to completion. It is simple and fair in order, but non-preemptive: once a process starts, it keeps the CPU until it finishes. The convoy effect is its weakness, like scooters stuck behind a slow truck on a one-lane road.

FCFS cannot starve a process, because every process reaches the front of the queue. Its problem is long waits, not endless ones.

Find the bug

Find the first wrong line

Each working has one root mistake. Click the first wrong line.

FCFS for P1 (arrives 0, burst 4) and P2 (arrives 6, burst 2).

Round 1 of 2

SJF and SRTF with worked averages

SJF (shortest job first) picks the ready process with the smallest burst time and runs it to completion; its preemptive form is SRTF.

The program below runs non-preemptive SJF and preemptive SRTF on the same four processes as before and prints each Gantt chart and average waiting time.

Example 4 · SJF and SRTF simulators

SjfSrtfDemo.javaJava
import java.util.ArrayList;import java.util.List;
record Proc(String name, int arrival, int burst) {}
public class SjfSrtfDemo {    // Non-preemptive SJF: when the CPU is free, run the shortest arrived job to completion.    static int[] sjf(List<Proc> ps, StringBuilder gantt) {        int n = ps.size(), time = 0, doneCount = 0;        int[] finish = new int[n];        boolean[] done = new boolean[n];        gantt.append(0);        while (doneCount < n) {            int pick = -1;            for (int i = 0; i < n; i++) {                Proc p = ps.get(i);                if (!done[i] && p.arrival() <= time && (pick == -1 || p.burst() < ps.get(pick).burst())) pick = i;            }            if (pick == -1) { time++; continue; }          // CPU idle            time += ps.get(pick).burst();            finish[pick] = time;            done[pick] = true;            doneCount++;            gantt.append(" [").append(ps.get(pick).name()).append("] ").append(time);        }        return finish;    }
    // SRTF: every millisecond, run the arrived job with the least remaining time.    static int[] srtf(List<Proc> ps, StringBuilder gantt) {        int n = ps.size(), time = 0, doneCount = 0;        int[] left = new int[n], finish = new int[n];        for (int i = 0; i < n; i++) left[i] = ps.get(i).burst();        String last = "";        gantt.append(0);        while (doneCount < n) {            int pick = -1;            for (int i = 0; i < n; i++) {                if (left[i] > 0 && ps.get(i).arrival() <= time && (pick == -1 || left[i] < left[pick])) pick = i;            }            String now = pick == -1 ? "idle" : ps.get(pick).name();            if (!now.equals(last) && time > 0) gantt.append(" [").append(last).append("] ").append(time);            last = now;            time++;            if (pick != -1 && --left[pick] == 0) {                finish[pick] = time;                doneCount++;            }        }        gantt.append(" [").append(last).append("] ").append(time);        return finish;    }
    static void report(String title, List<Proc> ps, int[] finish, StringBuilder gantt) {        int totalWait = 0, totalTat = 0;        for (int i = 0; i < ps.size(); i++) {            int tat = finish[i] - ps.get(i).arrival();            totalTat += tat;            totalWait += tat - ps.get(i).burst();        }        System.out.println(title + ": " + gantt);        System.out.printf("  avg waiting = %.2f, avg turnaround = %.2f%n",                (double) totalWait / ps.size(), (double) totalTat / ps.size());    }
    public static void main(String[] args) {        List<Proc> ps = new ArrayList<>(List.of(                new Proc("P1", 0, 8), new Proc("P2", 1, 4), new Proc("P3", 2, 9), new Proc("P4", 3, 5)));        StringBuilder g1 = new StringBuilder(), g2 = new StringBuilder();        report("SJF ", ps, sjf(ps, g1), g1);        report("SRTF", ps, srtf(ps, g2), g2);    }}
Output
SJF : 0 [P1] 8 [P2] 12 [P4] 17 [P3] 26
  avg waiting = 7.75, avg turnaround = 14.25
SRTF: 0 [P1] 1 [P2] 5 [P4] 10 [P1] 17 [P3] 26
  avg waiting = 6.50, avg turnaround = 13.00

What this code does

  • sjf picks the shortest arrived job only when the CPU is free; srtf re-checks every millisecond, so a newly arrived short job can take the CPU.
  • On the same data, FCFS averaged 8.75, SJF 7.75 and SRTF 6.50 waiting time. The strict < keeps the earlier-listed (earlier-arrived) process on ties.

SJF gives the lowest average waiting time of all non-preemptive methods when every burst is known. Shortest remaining time first (SRTF) is the preemptive form: when a new process arrives with less remaining time than the running one, the running one goes back to the ready queue.

The catch for both: real systems do not know burst times in advance, so they estimate them from past bursts, and long jobs can starve (wait for a very long time). On a tie, pick the process that arrived first unless the question says otherwise.

Predict the output

Total waiting time

Three jobs arrive at time 0 with bursts 6, 2 and 4. Pick the total waiting time.

Round 1 of 2

SJF runs the shortest job first.

int[] burst = {6, 2, 4};
java.util.Arrays.sort(burst);
int t = 0, wait = 0;
for (int b : burst) { wait += t; t += b; }
System.out.println(wait);

Preemptive vs non-preemptive scheduling

Preemptive scheduling lets the OS take the CPU away from a running process, for example when a shorter or higher-priority job arrives or its time slice ends.

In non-preemptive scheduling a process gives up the CPU only when it finishes or waits for I/O. The charts below show four processes (bursts 8, 4, 9 and 5) with and without preemption.

Text
Non-preemptive SJF: 0 [P1] 8 [P2] 12 [P4] 17 [P3] 26SRTF (preemptive):  0 [P1] 1 [P2] 5 [P4] 10 [P1] 17 [P3] 26At t=1, P2 (4 left) beats P1 (7 left), so P1 is preempted.

Preemption helps short jobs and response time. The price is more context switches, and shared data must be protected because a process can be interrupted at any moment. Revise: Synchronisation and semaphores (opens in a new tab)

Order of execution

How SRTF decides

Put the SRTF decisions for the chart above in order.

Worked numeric example with exact averages

Gantt chart is a timeline bar that shows which process held the CPU in each interval, from which every completion time is read.

The program below runs FCFS, SJF and SRTF on five processes: P1 (arrives 0, burst 3), P2 (2, 6), P3 (4, 4), P4 (6, 5) and P5 (8, 2). It prints each chart and its averages.

Example 5 · Worked example: FCFS, SJF and SRTF on five processes

WorkedSchedulingDemo.javaJava
import java.util.ArrayList;import java.util.List;
record Proc(String name, int arrival, int burst) {}
public class WorkedSchedulingDemo {    // Non-preemptive SJF: when the CPU is free, run the shortest arrived job to completion.    static int[] sjf(List<Proc> ps, StringBuilder gantt) {        int n = ps.size(), time = 0, doneCount = 0;        int[] finish = new int[n];        boolean[] done = new boolean[n];        gantt.append(0);        while (doneCount < n) {            int pick = -1;            for (int i = 0; i < n; i++) {                Proc p = ps.get(i);                if (!done[i] && p.arrival() <= time && (pick == -1 || p.burst() < ps.get(pick).burst())) pick = i;            }            if (pick == -1) { time++; continue; }          // CPU idle            time += ps.get(pick).burst();            finish[pick] = time;            done[pick] = true;            doneCount++;            gantt.append(" [").append(ps.get(pick).name()).append("] ").append(time);        }        return finish;    }
    // SRTF: every millisecond, run the arrived job with the least remaining time.    static int[] srtf(List<Proc> ps, StringBuilder gantt) {        int n = ps.size(), time = 0, doneCount = 0;        int[] left = new int[n], finish = new int[n];        for (int i = 0; i < n; i++) left[i] = ps.get(i).burst();        String last = "";        gantt.append(0);        while (doneCount < n) {            int pick = -1;            for (int i = 0; i < n; i++) {                if (left[i] > 0 && ps.get(i).arrival() <= time && (pick == -1 || left[i] < left[pick])) pick = i;            }            String now = pick == -1 ? "idle" : ps.get(pick).name();            if (!now.equals(last) && time > 0) gantt.append(" [").append(last).append("] ").append(time);            last = now;            time++;            if (pick != -1 && --left[pick] == 0) {                finish[pick] = time;                doneCount++;            }        }        gantt.append(" [").append(last).append("] ").append(time);        return finish;    }
    static void report(String title, List<Proc> ps, int[] finish, StringBuilder gantt) {        int totalWait = 0, totalTat = 0;        for (int i = 0; i < ps.size(); i++) {            int tat = finish[i] - ps.get(i).arrival();            totalTat += tat;            totalWait += tat - ps.get(i).burst();        }        System.out.println(title + ": " + gantt);        System.out.printf("  avg waiting = %.2f, avg turnaround = %.2f%n",                (double) totalWait / ps.size(), (double) totalTat / ps.size());    }
    public static void main(String[] args) {        List<Proc> ps = new ArrayList<>(List.of(new Proc("P1", 0, 3), new Proc("P2", 2, 6),                new Proc("P3", 4, 4), new Proc("P4", 6, 5), new Proc("P5", 8, 2)));        StringBuilder g0 = new StringBuilder("0"), g1 = new StringBuilder(), g2 = new StringBuilder();        int[] fcfs = new int[ps.size()];        int time = 0;        for (int i = 0; i < ps.size(); i++) {            time = Math.max(time, ps.get(i).arrival()) + ps.get(i).burst();            fcfs[i] = time;            g0.append(" [").append(ps.get(i).name()).append("] ").append(time);        }        report("FCFS", ps, fcfs, g0);        report("SJF ", ps, sjf(ps, g1), g1);        report("SRTF", ps, srtf(ps, g2), g2);    }}
Output
FCFS: 0 [P1] 3 [P2] 9 [P3] 13 [P4] 18 [P5] 20
  avg waiting = 4.60, avg turnaround = 8.60
SJF : 0 [P1] 3 [P2] 9 [P5] 11 [P3] 15 [P4] 20
  avg waiting = 3.60, avg turnaround = 7.60
SRTF: 0 [P1] 3 [P2] 4 [P3] 8 [P5] 10 [P2] 15 [P4] 20
  avg waiting = 3.20, avg turnaround = 7.20

What this code does

  • Check: in every row, average TAT − average WT = 4.00, the average burst (20 ÷ 5). Use this check in the exam to catch arithmetic slips.
  • SRTF preempts P2 at time 4: P2 still needs 5 ms and the new P3 needs only 4. At 8, P5 (2 ms) beats P2 and P4 (5 ms each); at 10 the tie between P2 and P4 goes to P2, which arrived first.

FCFS completions are 3, 9, 13, 18 and 20, so its average waiting time is 4.6. Non-preemptive SJF runs P5 before P3 and P4 at time 9 and gets 3.6; SRTF lowers it to 3.2. Use the same routine for any numerical:

  • Draw the Gantt chart, marking every arrival.
  • Read off each completion time.
  • TAT = completion − arrival; WT = TAT − burst.
  • Average each column and check: average TAT − average WT = average burst.

Predict the output

The quick check

Use the check from the steps above.

Five processes: total turnaround 46 ms and total burst 20 ms. What is the average waiting time?

int totalTat = 46, totalBurst = 20;
System.out.println((totalTat - totalBurst) / 5.0);

Next step

Check your understanding

12 quick questions