Skip to lesson

Processes, threads, process states and context switching

In almost every campus and off-campus technical round, the first operating-system question is "process vs thread?". The interviewer is checking that you can say what is shared and what is private, not just recite definitions.

What an OS does: kernel, user mode and system calls

Kernel is the core of the operating system that stays in memory, runs in kernel mode and controls the CPU, memory, disks and devices.

The program below asks the operating system three questions through Java: its name, how many CPU cores it offers, and the id of this running program.

Example 1 · Asking the OS through Java

OsInfoDemo.javaJava
public class OsInfoDemo {    public static void main(String[] args) {        System.out.println("OS name: " + System.getProperty("os.name"));        System.out.println("CPU cores the OS gives Java: " + Runtime.getRuntime().availableProcessors());        System.out.println("This process id: " + ProcessHandle.current().pid());        System.out.println("Threads in this process right now: " + Thread.activeCount());    }}
Sample output
OS name: Windows 11
CPU cores the OS gives Java: 8
This process id: 15432
Threads in this process right now: 1

What this code does

  • Each line is answered by the OS: Java asks the kernel (through system calls inside the JVM) for the core count and the process id.
  • Your values will differ: the OS name, core count and process id depend on your computer and on this run.

The OS is a resource manager: it decides which program runs, how much memory each gets and who may open which file. In kernel mode the CPU lets code do anything, such as talk to the disk; in user mode, where your programs run, such actions are blocked.

A program gets a blocked action done through a system call: a controlled request to the kernel, such as read, write, fork or exit. Java hides these behind its library; Files.readString ends up in a read system call.

Find the bug

Spot the wrong line

Each spoken answer has one wrong line. Click it.

Answer to "What is a system call?"

Round 1 of 2

Process vs thread: memory, cost, communication

Thread is a path of execution inside a process; threads of one process share its code, heap and open files, but each thread has its own stack, program counter and registers.

Two threads of one process write into the same array, and the main thread reads both results straight away, with no pipes or sockets in between.

Example 2 · Two threads share one process's memory

SharedMemoryDemo.javaJava
public class SharedMemoryDemo {    static int[] votes = new int[2];   // on the heap: shared by all threads
    public static void main(String[] args) throws InterruptedException {        Thread hostelA = new Thread(() -> {            for (int i = 0; i < 300; i++) votes[0]++;        });        Thread hostelB = new Thread(() -> {            for (int i = 0; i < 450; i++) votes[1]++;        });        hostelA.start();        hostelB.start();        hostelA.join();   // wait for both threads to finish        hostelB.join();
        System.out.println("Hostel A votes: " + votes[0]);        System.out.println("Hostel B votes: " + votes[1]);        System.out.println("Main thread sees both: " + (votes[0] + votes[1]));    }}
Output
Hostel A votes: 300
Hostel B votes: 450
Main thread sees both: 750

What this code does

  • Both threads write into the same votes array, and main reads their results directly. No pipes or sockets are needed because threads share the heap.
  • Each thread updates its own slot, so there is no conflict. When two threads update the same value, a race condition appears; the Synchronisation and semaphores lesson later in this module covers that.

A process is a program in execution, with its own address space (code, data, heap and stack), open files and an id. The four differences interviewers ask for:

  • Memory: a process has a separate address space; threads share the heap and have their own stacks.
  • Cost: creating or switching a thread is usually cheaper than a process.
  • Communication: threads use shared objects; processes need inter-process communication (IPC) such as pipes, sockets or shared memory.
  • Failure: a crashed process is isolated; an uncaught error can stop a whole multi-threaded process.

Revise: Creating a thread with Runnable (opens in a new tab)

Predict the output

What do the threads see?

Pick the output. Remember what threads share.

Round 1 of 2

A thread changes a static field and main waits for it.

public class StockDemo {
static int stock = 1;
public static void main(String[] args) throws Exception {
Thread t = new Thread(() -> stock = stock + 10);
t.start();
t.join();
System.out.println(stock);
}
}

Process states and the PCB

Process state is the stage of a process's life: new, ready, running, waiting or terminated, and the scheduler and I/O events move it between them.

The program below walks one process through its states and records each move, with a small Pcb class holding what the kernel needs to resume it.

Process state diagram. A new process is admitted to ready. The scheduler dispatches a ready process to running. A running process goes back to ready when its time slice ends, to waiting when it asks for I/O, and to terminated when it exits. After I/O it goes to ready, never straight to running.

Example 3 · A process moving through its states

ProcessStateDemo.javaJava
import java.util.ArrayList;import java.util.List;
enum State { NEW, READY, RUNNING, WAITING, TERMINATED }
class Pcb {    final int pid;    State state = State.NEW;    int programCounter = 0;    final List<String> history = new ArrayList<>();
    Pcb(int pid) {        this.pid = pid;        history.add(state.name());    }
    void moveTo(State next) {        state = next;        history.add(next.name());    }}
public class ProcessStateDemo {    public static void main(String[] args) {        Pcb p = new Pcb(101);        p.moveTo(State.READY);       // admitted by the OS        p.moveTo(State.RUNNING);     // picked by the scheduler        p.programCounter = 40;        p.moveTo(State.WAITING);     // asks to read a file        p.moveTo(State.READY);        p.moveTo(State.RUNNING);        p.moveTo(State.TERMINATED);
        System.out.println("PID " + p.pid + ": " + String.join(" -> ", p.history));        System.out.println("Resumed at program counter " + p.programCounter);    }}
Output
PID 101: NEW -> READY -> RUNNING -> WAITING -> READY -> RUNNING -> TERMINATED
Resumed at program counter 40

What this code does

  • Pcb keeps the fields the kernel needs to pause and resume a process: id, state and program counter (a real PCB has much more).
  • After waiting for I/O the process goes back to READY, not straight to RUNNING: it must wait for the scheduler to pick it again.

A process starts new, is admitted to ready (waiting for the CPU), becomes running when the scheduler picks it, moves to waiting when it needs I/O, and ends terminated. Only one process per CPU core is running at any moment.

The PCB (process control block) holds the process id, state, program counter, saved registers, priority, the page table, the list of open files and the CPU time used.

Order of execution

A process reads a file

Put the states of one process in order, from creation to exit.

Context switching and its cost

Context switch is the kernel stopping one process or thread and starting another: it saves the running one's state in its PCB and loads the next one's state.

The program below shows how much CPU time context switching wastes for four time-slice lengths, assuming each switch costs 5 microseconds.

Example 4 · How much CPU time switching wastes

SwitchCostDemo.javaJava
public class SwitchCostDemo {    static double usefulPercent(double sliceMicros, double switchMicros) {        return 100.0 * sliceMicros / (sliceMicros + switchMicros);    }
    public static void main(String[] args) {        double switchCost = 5;   // microseconds per context switch (assumed)        double[] slices = {10, 100, 1000, 10000};        for (double slice : slices) {            System.out.printf("Slice %6.0f us -> %.1f%% useful work%n", slice, usefulPercent(slice, switchCost));        }    }}
Output
Slice     10 us -> 66.7% useful work
Slice    100 us -> 95.2% useful work
Slice   1000 us -> 99.5% useful work
Slice  10000 us -> 100.0% useful work

What this code does

  • Every slice of work is followed by one switch. With a 10 µs slice, a third of the CPU goes to switching; with 10 ms it is negligible.
  • This is the trade-off schedulers face: switch often for quick response, or rarely for less overhead. The 5 µs figure is an assumption for the sum.

During a switch no user work is done, so it is pure overhead. Switching between processes also changes the memory map, which flushes or weakens the caches and the TLB (a cache of address translations). Threads of one process skip that change, which is why their switch is cheaper.

Exact costs vary by hardware and OS: often a few microseconds, plus the cache effects afterwards.

Predict the output

How much work is useful?

A switch costs 5 microseconds. Pick the useful percentage.

Round 1 of 2

Time slice 20 microseconds.

double slice = 20, sw = 5;
System.out.println(100 * slice / (slice + sw));

Interview questions with model answers

The program below shows the states a Java thread passes through, which map closely onto the operating system states.

Example 5 · Java thread states you can observe

ThreadStateDemo.javaJava
public class ThreadStateDemo {    public static void main(String[] args) throws InterruptedException {        Thread worker = new Thread(() -> {            int sum = 0;            for (int i = 1; i <= 100; i++) sum += i;        });        System.out.println("Before start: " + worker.getState());        worker.start();        worker.join();        System.out.println("After join:   " + worker.getState());        System.out.println("Main thread:  " + Thread.currentThread().getState());    }}
Output
Before start: NEW
After join:   TERMINATED
Main thread:  RUNNABLE

What this code does

  • A created but not started thread is NEW; after it finishes it is TERMINATED, matching the OS states.
  • The main thread is RUNNABLE while it prints. Java uses one state for both ready and running.

Java uses NEW, RUNNABLE (ready or running; Java does not separate them), BLOCKED, WAITING, TIMED_WAITING and TERMINATED. Interviewers like this link because it connects OS theory to code you write.

Revise: Creating a thread with Runnable (opens in a new tab) | Virtual threads in Java 21 (opens in a new tab)

Next step

Check your understanding

12 quick questions