Back to Thread Basics & Overview
Q6Question 6 of 8

What are threads, processes, and context switching in Java

Answer: A process is an independent running program with its own memory, a thread is a lightweight execution unit within that process sharing the same memory, and context switching is the OS mechanism that saves one thread's state and restores another to share CPU time.

Key Concepts
  • A process is an independent running program with its own memory space, and a thread is a lightweight unit of execution within a process that shares the same memory.
  • Java provides two ways to create platform threads: extending the Thread class or implementing the Runnable interface, with Runnable being preferred because Java does not support multiple inheritance.
  • Every Java thread maps to an OS-level thread (platform thread), and the OS scheduler decides which thread runs on which CPU core.
  • Context switching is when the OS saves the state of one thread and restores another, which costs 1 to 10 microseconds per switch depending on hardware.
  • Java threads have six states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.
  • Virtual threads (Java 21+) are lightweight threads managed by the JVM, not the OS, allowing millions of concurrent threads for IO-bound workloads.
  • Thread safety requires synchronization when multiple threads access shared mutable state, otherwise race conditions corrupt data.

Definition

A process is an independent running program with its own memory, a thread is a lightweight execution unit within that process sharing the same memory, and context switching is the OS mechanism that saves one thread's state and restores another to share CPU time.
  • Process is an independent instance of a running program with its own memory space (heap, stack, code segment), managed by the operating system.
  • Thread is the smallest unit of execution within a process; all threads in a process share the same heap memory but have their own stack.
  • Platform thread is a Java thread that maps one-to-one to an OS-level (kernel) thread, scheduled by the operating system.
  • Virtual thread (Java 21+) is a lightweight thread managed by the JVM runtime, not by the OS, designed for high-concurrency IO-bound tasks.
  • Context switching is the OS operation of saving the registers, program counter, and stack pointer of the current thread, and restoring those of the next thread to run on the same CPU core.
  • Thread state is the lifecycle stage of a thread: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED.

Think of a National Bank of India branch. The branch building is a process: it has its own space, its own resources (desks, safes, cash), and runs independently from other branches. Each teller window inside the branch is a thread: all tellers share the same safe (heap memory) and the same building (address space), but each teller has their own notepad (thread stack) to track their current customer. Context switching is the branch manager rotating tellers between windows: the manager saves where one teller left off (register state), moves them to another task, and brings in a different teller. If only one teller works at a time, the branch is single-threaded. With multiple tellers serving customers simultaneously, the branch is multi-threaded.

Understanding the Concepts

What is a process?

A process is an independent running program managed by the operating system. When you start a Java application with java com.bank.App, the OS creates a new process. Each process has its own virtual address space, heap memory, code segment, and at least one thread (the main thread). Processes are isolated from each other: one process cannot directly access another process's memory.

In a banking system, each microservice (account service, payment service, fraud detection) runs as a separate process. If the fraud detection service crashes, the account service keeps running because they are in different processes.

JAVA
package com.bank.concurrency;

public class ProcessInfoDemo {
    public static void main(String[] args) {
        ProcessHandle current = ProcessHandle.current();
        System.out.println("=== Current Process ===");
        System.out.println("PID:     " + current.pid());
        System.out.println("Command: " + current.info().command().orElse("unknown"));
        System.out.println("User:    " + current.info().user().orElse("unknown"));
        System.out.println();

        // Each JVM instance is a separate process
        System.out.println("=== Process vs Thread ===");
        System.out.println("This JVM is one process with PID " + current.pid());
        System.out.println("Main thread: " + Thread.currentThread().getName());
        System.out.println();

        // Show available processors (CPUs)
        int cpus = Runtime.getRuntime().availableProcessors();
        System.out.println("Available CPUs: " + cpus);
        System.out.println("Max memory:     " + Runtime.getRuntime().maxMemory() / (1024 * 1024) + " MB");
        System.out.println();

        System.out.println("Key facts:");
        System.out.println("  1. Each process has its own memory space (isolated)");
        System.out.println("  2. Threads within a process share the same heap");
        System.out.println("  3. Process creation is expensive (new address space)");
        System.out.println("  4. Thread creation is cheaper (shared address space)");
    }
}
TEXT
Expected output:
=== Current Process ===
PID:     42156
Command: /usr/lib/jvm/java-25/bin/java
User:    rajesh

=== Process vs Thread ===
This JVM is one process with PID 42156
Main thread: main

Available CPUs: 8
Max memory:     4096 MB

Key facts:
  1. Each process has its own memory space (isolated)
  2. Threads within a process share the same heap
  3. Process creation is expensive (new address space)
  4. Thread creation is cheaper (shared address space)

What is a thread?

A thread is the smallest unit of execution inside a process. Every Java application starts with one thread called main. You can create additional threads to perform work concurrently: one thread handles a customer deposit while another thread processes a withdrawal.

All threads in the same process share the heap memory (objects, arrays) but each thread has its own stack (local variables, method call frames). This sharing is both the strength and the danger of threads: sharing data is fast, but uncoordinated access leads to race conditions.

JAVA
package com.bank.concurrency;

public class ThreadBasicsDemo {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Main thread: " + Thread.currentThread().getName());
        System.out.println("Main thread ID: " + Thread.currentThread().threadId());
        System.out.println();

        // Create a thread for deposit processing
        Thread depositThread = new Thread(() -> {
            System.out.println("Deposit thread: " + Thread.currentThread().getName());
            System.out.println("  Processing deposit for SAV2001: 25,000.00 INR");
            System.out.println("  Thread ID: " + Thread.currentThread().threadId());
        }, "deposit-processor");

        // Create a thread for withdrawal processing
        Thread withdrawalThread = new Thread(() -> {
            System.out.println("Withdrawal thread: " + Thread.currentThread().getName());
            System.out.println("  Processing withdrawal for SAV2002: 10,000.00 INR");
            System.out.println("  Thread ID: " + Thread.currentThread().threadId());
        }, "withdrawal-processor");

        depositThread.start();
        withdrawalThread.start();

        // Wait for both threads to finish
        depositThread.join();
        withdrawalThread.join();

        System.out.println();
        System.out.println("Both transactions completed.");
    }
}
TEXT
Expected output:
Main thread: main
Main thread ID: 1

Deposit thread: deposit-processor
  Processing deposit for SAV2001: 25,000.00 INR
  Thread ID: 21
Withdrawal thread: withdrawal-processor
  Processing withdrawal for SAV2002: 10,000.00 INR
  Thread ID: 22

Both transactions completed.

How are threads different from processes?

FeatureProcessThread
MemoryOwn address space (isolated)Shares heap with other threads
Creation costExpensive (OS allocates new address space)Cheaper (shares existing address space)
CommunicationInter-process communication (sockets, pipes, shared memory)Direct access to shared variables
Crash impactOne process crash does not affect othersOne thread crash can terminate the entire process
SchedulingScheduled by the OSScheduled by the OS (platform threads) or JVM (virtual threads)
OverheadHeavy (100+ KB per process for metadata)Lighter (platform thread ~1 MB stack, virtual thread ~1 KB)
ExampleAccount service and payment service as separate JVMsDeposit thread and withdrawal thread in the same JVM
JAVA
package com.bank.concurrency;

public class ProcessVsThreadDemo {
    // Shared variable: all threads see this (shared heap)
    private static int sharedCounter = 0;

    public static void main(String[] args) throws InterruptedException {
        System.out.println("=== Threads Share Memory ===");

        Thread threadA = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                sharedCounter++;
            }
            System.out.println("Thread A finished, counter = " + sharedCounter);
        }, "thread-A");

        Thread threadB = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                sharedCounter++;
            }
            System.out.println("Thread B finished, counter = " + sharedCounter);
        }, "thread-B");

        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();

        System.out.println("Final counter: " + sharedCounter);
        System.out.println("Expected: 2000 (but may be less due to race condition)");
        System.out.println();

        System.out.println("=== Key Differences ===");
        System.out.println("Process: own memory, isolated, expensive to create");
        System.out.println("Thread:  shared memory, not isolated, cheap to create");
        System.out.println();
        System.out.println("In banking:");
        System.out.println("  Process: account-service and payment-service are separate JVMs");
        System.out.println("  Thread:  100 concurrent deposit requests in the same account-service");
    }
}
TEXT
Expected output:
=== Threads Share Memory ===
Thread A finished, counter = 1834
Thread B finished, counter = 2000
Final counter: 2000
Expected: 2000 (but may be less due to race condition)

=== Key Differences ===
Process: own memory, isolated, expensive to create
Thread:  shared memory, not isolated, cheap to create

In banking:
  Process: account-service and payment-service are separate JVMs
  Thread:  100 concurrent deposit requests in the same account-service

The counter result may vary on each run. Without synchronization, both threads read and write sharedCounter at the same time, causing lost updates.

How do you create threads in Java?

Java provides multiple ways to create threads. The three main approaches are extending the Thread class, implementing Runnable, and implementing Callable (which can return a result). In modern Java (21+), you can also use virtual threads.

Approach 1: Extend Thread (not recommended)

JAVA
package com.bank.concurrency;

public class ExtendThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        DepositThread deposit = new DepositThread("SAV2001", 50000);
        deposit.start();
        deposit.join();
    }
}

class DepositThread extends Thread {
    private final String accountId;
    private final long amount;

    DepositThread(String accountId, long amount) {
        super("deposit-" + accountId);
        this.accountId = accountId;
        this.amount = amount;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()
            + ": Depositing " + amount + " INR to " + accountId);
    }
}
TEXT
Expected output:
deposit-SAV2001: Depositing 50000 INR to SAV2001

Approach 2: Implement Runnable (preferred)

JAVA
package com.bank.concurrency;

public class RunnableDemo {
    public static void main(String[] args) throws InterruptedException {
        Runnable withdrawalTask = () -> {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + ": Withdrawing 10,000 INR from SAV2002");
        };

        Thread thread = new Thread(withdrawalTask, "withdrawal-SAV2002");
        thread.start();
        thread.join();

        System.out.println("Runnable is preferred because:");
        System.out.println("  1. Your class can extend another class (no multiple inheritance limit)");
        System.out.println("  2. Separates the task from the thread mechanism");
        System.out.println("  3. Works with ExecutorService and thread pools");
    }
}
TEXT
Expected output:
withdrawal-SAV2002: Withdrawing 10,000 INR from SAV2002
Runnable is preferred because:
  1. Your class can extend another class (no multiple inheritance limit)
  2. Separates the task from the thread mechanism
  3. Works with ExecutorService and thread pools

Approach 3: Implement Callable (returns a result)

JAVA
package com.bank.concurrency;

import java.math.BigDecimal;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CallableDemo {
    public static void main(String[] args) throws Exception {
        Callable<BigDecimal> balanceCheck = () -> {
            System.out.println(Thread.currentThread().getName()
                + ": Checking balance for SAV2001");
            Thread.sleep(100); // Simulate database call
            return new BigDecimal("250000.00");
        };

        FutureTask<BigDecimal> futureTask = new FutureTask<>(balanceCheck);
        Thread thread = new Thread(futureTask, "balance-checker");
        thread.start();

        // get() blocks until the result is available
        BigDecimal balance = futureTask.get();
        System.out.println("Balance for SAV2001: " + balance + " INR");
    }
}
TEXT
Expected output:
balance-checker: Checking balance for SAV2001
Balance for SAV2001: 250000.00 INR

What are thread states in Java?

A Java thread goes through six states during its lifecycle, defined in the Thread.State enum.

  1. NEW: Thread object created but start() not yet called.
  2. RUNNABLE: Thread is running or ready to run. The OS scheduler decides when it gets CPU time.
  3. BLOCKED: Thread is waiting to acquire a monitor lock (synchronized block).
  4. WAITING: Thread is waiting indefinitely for another thread (wait(), join(), LockSupport.park()).
  5. TIMED_WAITING: Thread is waiting for a specified time (sleep(), wait(timeout), join(timeout)).
  6. TERMINATED: Thread has finished its run() method.
JAVA
package com.bank.concurrency;

public class ThreadStatesDemo {
    private static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        // NEW state
        Thread transferThread = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("Transfer thread: entering TIMED_WAITING");
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }, "transfer-processor");

        System.out.println("State after new Thread(): " + transferThread.getState());

        // RUNNABLE state
        transferThread.start();
        Thread.sleep(50); // Give it time to start
        System.out.println("State after start():      " + transferThread.getState());

        // TIMED_WAITING state (sleeping)
        Thread.sleep(200);
        System.out.println("State during sleep():     " + transferThread.getState());

        // Wait for completion
        transferThread.join();
        System.out.println("State after completion:   " + transferThread.getState());

        System.out.println();
        System.out.println("Thread state transitions:");
        System.out.println("  NEW -> RUNNABLE -> TIMED_WAITING -> RUNNABLE -> TERMINATED");
    }
}
TEXT
Expected output:
State after new Thread(): NEW
State after start():      RUNNABLE
Transfer thread: entering TIMED_WAITING
State during sleep():     TIMED_WAITING
State after completion:   TERMINATED

Thread state transitions:
  NEW -> RUNNABLE -> TIMED_WAITING -> RUNNABLE -> TERMINATED

What is context switching?

Context switching is the mechanism the OS uses to share CPU cores among multiple threads. When the OS scheduler decides to pause one thread and run another, it saves the current thread's state (registers, program counter, stack pointer) and restores the next thread's state. This operation costs 1 to 10 microseconds per switch, depending on the hardware and OS.

In a banking system processing thousands of transactions per second, excessive context switching degrades performance. If you have 1,000 threads on an 8-core machine, the OS spends significant time switching between them instead of doing useful work.

JAVA
package com.bank.concurrency;

public class ContextSwitchingDemo {
    public static void main(String[] args) throws InterruptedException {
        int cpuCount = Runtime.getRuntime().availableProcessors();
        System.out.println("Available CPU cores: " + cpuCount);
        System.out.println();

        // Measure work with optimal thread count (= CPU cores)
        long optimalTime = measureWork(cpuCount, 10_000_000);
        System.out.println("Optimal (" + cpuCount + " threads):  " + optimalTime + " ms");

        // Measure work with excessive thread count
        int excessiveCount = cpuCount * 50;
        long excessiveTime = measureWork(excessiveCount, 10_000_000 / excessiveCount * cpuCount);
        System.out.println("Excessive (" + excessiveCount + " threads): " + excessiveTime + " ms");

        System.out.println();
        System.out.println("More threads than CPU cores causes context switching overhead.");
        System.out.println("For CPU-bound work, use thread count = CPU core count.");
        System.out.println("For IO-bound work, more threads are acceptable because");
        System.out.println("  threads spend most time waiting, not using the CPU.");
    }

    private static long measureWork(int threadCount, int workPerThread) throws InterruptedException {
        Thread[] threads = new Thread[threadCount];
        long start = System.currentTimeMillis();

        for (int i = 0; i < threadCount; i++) {
            final int work = workPerThread;
            threads[i] = new Thread(() -> {
                // CPU-bound work: simple arithmetic
                long sum = 0;
                for (int j = 0; j < work; j++) {
                    sum += j;
                }
                // Prevent JIT from optimizing away the loop
                if (sum < 0) System.out.println(sum);
            });
            threads[i].start();
        }

        for (Thread t : threads) {
            t.join();
        }

        return System.currentTimeMillis() - start;
    }
}
TEXT
Expected output:
Available CPU cores: 8

Optimal (8 threads):  45 ms
Excessive (400 threads): 112 ms

More threads than CPU cores causes context switching overhead.
For CPU-bound work, use thread count = CPU core count.
For IO-bound work, more threads are acceptable because
  threads spend most time waiting, not using the CPU.

The exact numbers depend on hardware, but the pattern is consistent: more threads than CPU cores slows down CPU-bound work because of context switching overhead.

What about virtual threads (Java 21+)?

Virtual threads are lightweight threads managed by the JVM, not by the OS. A platform thread maps one-to-one to an OS thread and costs about 1 MB of stack memory. A virtual thread costs about 1 KB and is multiplexed onto a small pool of platform threads (carrier threads) by the JVM scheduler.

Virtual threads are designed for IO-bound workloads. When a virtual thread blocks on IO (database query, HTTP call, file read), the JVM unmounts it from the carrier thread and mounts another virtual thread. This means you can have millions of virtual threads without running out of OS threads.

FeaturePlatform ThreadVirtual Thread
Managed byOperating systemJVM runtime
Memory cost~1 MB per thread (stack)~1 KB per thread
Max practical countThousands (limited by OS)Millions (limited by heap)
SchedulingOS schedulerJVM ForkJoinPool scheduler
Best forCPU-bound workIO-bound work
Blocking behaviorBlocks OS threadUnmounts from carrier, no OS thread blocked
Creationnew Thread() or Executors.newFixedThreadPoolThread.ofVirtual() or Executors.newVirtualThreadPerTaskExecutor
JAVA
package com.bank.concurrency;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.CountDownLatch;

public class VirtualThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        int taskCount = 10_000;

        // Platform threads: limited by OS
        System.out.println("=== Platform Threads ===");
        Instant start = Instant.now();
        try (var executor = Executors.newFixedThreadPool(100)) {
            CountDownLatch latch = new CountDownLatch(taskCount);
            for (int i = 0; i < taskCount; i++) {
                final String accountId = "SAV" + (2001 + i % 100);
                executor.submit(() -> {
                    try {
                        // Simulate IO: database balance check
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        latch.countDown();
                    }
                });
            }
            latch.await();
        }
        long platformTime = Duration.between(start, Instant.now()).toMillis();
        System.out.println("  " + taskCount + " tasks with 100 platform threads: " + platformTime + " ms");

        // Virtual threads: one per task
        System.out.println();
        System.out.println("=== Virtual Threads ===");
        start = Instant.now();
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            CountDownLatch latch = new CountDownLatch(taskCount);
            for (int i = 0; i < taskCount; i++) {
                executor.submit(() -> {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        latch.countDown();
                    }
                });
            }
            latch.await();
        }
        long virtualTime = Duration.between(start, Instant.now()).toMillis();
        System.out.println("  " + taskCount + " tasks with virtual threads: " + virtualTime + " ms");

        System.out.println();
        System.out.println("Virtual threads handle IO-bound tasks more efficiently");
        System.out.println("because blocked threads do not occupy OS threads.");
    }
}
TEXT
Expected output:
=== Platform Threads ===
  10000 tasks with 100 platform threads: 1024 ms

=== Virtual Threads ===
  10000 tasks with virtual threads: 48 ms

Virtual threads handle IO-bound tasks more efficiently
because blocked threads do not occupy OS threads.

Virtual threads complete much faster because all 10,000 tasks run concurrently. With 100 platform threads, only 100 tasks can sleep at the same time, so the rest must wait in the queue.

What are common mistakes with threads?

The most common mistakes are calling run() instead of start(), not handling InterruptedException, and sharing mutable state without synchronization.

Wrong: calling run() instead of start()

JAVA
package com.bank.concurrency;

public class WrongRunCallDemo {
    public static void main(String[] args) {
        Thread depositThread = new Thread(() -> {
            System.out.println("Running in: " + Thread.currentThread().getName());
            System.out.println("Processing deposit for SAV2001");
        }, "deposit-thread");

        System.out.println("WRONG: Calling run() directly");
        depositThread.run();  // WRONG: runs in main thread, not a new thread
        System.out.println("  (Executed in main thread, not in deposit-thread)");
    }
}
TEXT
Expected output:
WRONG: Calling run() directly
Running in: main
Processing deposit for SAV2001
  (Executed in main thread, not in deposit-thread)

Correct: calling start() to launch a new thread

JAVA
package com.bank.concurrency;

public class CorrectStartCallDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread depositThread = new Thread(() -> {
            System.out.println("Running in: " + Thread.currentThread().getName());
            System.out.println("Processing deposit for SAV2001");
        }, "deposit-thread");

        System.out.println("CORRECT: Calling start()");
        depositThread.start(); // CORRECT: runs in a new thread
        depositThread.join();
        System.out.println("  (Executed in deposit-thread, a separate thread)");
    }
}
TEXT
Expected output:
CORRECT: Calling start()
Running in: deposit-thread
Processing deposit for SAV2001
  (Executed in deposit-thread, a separate thread)

Wrong: swallowing InterruptedException

JAVA
package com.bank.concurrency;

public class WrongInterruptHandling {
    public static void main(String[] args) {
        Thread worker = new Thread(() -> {
            try {
                System.out.println("Worker: processing transfer for Priya");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // WRONG: swallowing the interrupt, thread loses its interrupted status
                System.out.println("WRONG: Caught InterruptedException but did nothing");
                System.out.println("  The thread no longer knows it was interrupted");
                System.out.println("  isInterrupted = " + Thread.currentThread().isInterrupted());
            }
        }, "transfer-worker");

        worker.start();
        try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        worker.interrupt();
        try { worker.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    }
}
TEXT
Expected output:
Worker: processing transfer for Priya
WRONG: Caught InterruptedException but did nothing
  The thread no longer knows it was interrupted
  isInterrupted = false

Correct: restoring the interrupt flag

JAVA
package com.bank.concurrency;

public class CorrectInterruptHandling {
    public static void main(String[] args) {
        Thread worker = new Thread(() -> {
            try {
                System.out.println("Worker: processing transfer for Priya");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // CORRECT: restore the interrupt flag
                Thread.currentThread().interrupt();
                System.out.println("CORRECT: Restored interrupt flag");
                System.out.println("  isInterrupted = " + Thread.currentThread().isInterrupted());
                System.out.println("  Callers above can now detect the interrupt");
            }
        }, "transfer-worker");

        worker.start();
        try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        worker.interrupt();
        try { worker.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    }
}
TEXT
Expected output:
Worker: processing transfer for Priya
CORRECT: Restored interrupt flag
  isInterrupted = true
  Callers above can now detect the interrupt

What is a complete banking project with multi-threaded transaction processing?

This project builds a multi-threaded transaction processor for National Bank of India. Multiple threads process deposits and withdrawals concurrently on a shared account balance, with proper synchronization.

Project structure

DIAGRAM
banking-transaction-processor/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── com/
                └── bank/
                    ├── model/
                    │   └── BankAccount.java           (thread-safe account)
                    ├── service/
                    │   └── TransactionProcessor.java   (multi-threaded processor)
                    └── TransactionApp.java             (main class)

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>banking-transaction-processorsyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
    syn-kw"><packagingsyn-kw">>jarsyn-kw"></packagingsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
        syn-kw"><maven.compiler.sourcesyn-kw">>25syn-kw"></maven.compiler.sourcesyn-kw">>
        syn-kw"><maven.compiler.targetsyn-kw">>25syn-kw"></maven.compiler.targetsyn-kw">>
    syn-kw"></propertiessyn-kw">>
syn-kw"></projectsyn-kw">>

BankAccount.java

JAVA
package com.bank.model;

import java.math.BigDecimal;

public class BankAccount {
    private final String accountId;
    private final String holderName;
    private BigDecimal balance;

    public BankAccount(String accountId, String holderName, BigDecimal initialBalance) {
        this.accountId = accountId;
        this.holderName = holderName;
        this.balance = initialBalance;
    }

    public synchronized void deposit(BigDecimal amount) {
        balance = balance.add(amount);
        System.out.println("  [" + Thread.currentThread().getName() + "] Deposit "
            + amount + " to " + accountId + ", balance: " + balance);
    }

    public synchronized boolean withdraw(BigDecimal amount) {
        if (balance.compareTo(amount) < 0) {
            System.out.println("  [" + Thread.currentThread().getName()
                + "] Insufficient funds in " + accountId
                + ", requested: " + amount + ", available: " + balance);
            return false;
        }
        balance = balance.subtract(amount);
        System.out.println("  [" + Thread.currentThread().getName() + "] Withdraw "
            + amount + " from " + accountId + ", balance: " + balance);
        return true;
    }

    public synchronized BigDecimal getBalance() {
        return balance;
    }

    public String getAccountId() { return accountId; }
    public String getHolderName() { return holderName; }
}

TransactionProcessor.java

JAVA
package com.bank.service;

import com.bank.model.BankAccount;
import java.math.BigDecimal;

public class TransactionProcessor implements Runnable {
    private final BankAccount account;
    private final String type; // DEPOSIT or WITHDRAW
    private final BigDecimal amount;
    private final int repeatCount;

    public TransactionProcessor(BankAccount account, String type,
                                 BigDecimal amount, int repeatCount) {
        this.account = account;
        this.type = type;
        this.amount = amount;
        this.repeatCount = repeatCount;
    }

    @Override
    public void run() {
        for (int i = 0; i < repeatCount; i++) {
            if ("DEPOSIT".equals(type)) {
                account.deposit(amount);
            } else {
                account.withdraw(amount);
            }
        }
    }
}

TransactionApp.java

JAVA
package com.bank;

import com.bank.model.BankAccount;
import com.bank.service.TransactionProcessor;
import java.math.BigDecimal;

public class TransactionApp {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("National Bank of India - Transaction Processor");
        System.out.println("===============================================");
        System.out.println();

        BankAccount rajeshAccount = new BankAccount(
            "SAV2001", "Rajesh Kumar", new BigDecimal("100000.00"));

        System.out.println("Initial balance: " + rajeshAccount.getBalance() + " INR");
        System.out.println();

        // 3 deposit threads, each depositing 10,000 three times
        Thread deposit1 = new Thread(new TransactionProcessor(
            rajeshAccount, "DEPOSIT", new BigDecimal("10000.00"), 3), "depositor-1");
        Thread deposit2 = new Thread(new TransactionProcessor(
            rajeshAccount, "DEPOSIT", new BigDecimal("10000.00"), 3), "depositor-2");
        Thread deposit3 = new Thread(new TransactionProcessor(
            rajeshAccount, "DEPOSIT", new BigDecimal("10000.00"), 3), "depositor-3");

        // 2 withdrawal threads, each withdrawing 15,000 twice
        Thread withdraw1 = new Thread(new TransactionProcessor(
            rajeshAccount, "WITHDRAW", new BigDecimal("15000.00"), 2), "withdrawer-1");
        Thread withdraw2 = new Thread(new TransactionProcessor(
            rajeshAccount, "WITHDRAW", new BigDecimal("15000.00"), 2), "withdrawer-2");

        // Start all threads
        deposit1.start();
        deposit2.start();
        deposit3.start();
        withdraw1.start();
        withdraw2.start();

        // Wait for all threads
        deposit1.join();
        deposit2.join();
        deposit3.join();
        withdraw1.join();
        withdraw2.join();

        System.out.println();
        System.out.println("Final balance: " + rajeshAccount.getBalance() + " INR");
        System.out.println("Expected: 100000 + (9 * 10000) - (4 * 15000) = 130000.00 INR");
    }
}
TEXT
Expected output:
National Bank of India - Transaction Processor
===============================================

Initial balance: 100000.00 INR

  [depositor-1] Deposit 10000.00 to SAV2001, balance: 110000.00
  [depositor-1] Deposit 10000.00 to SAV2001, balance: 120000.00
  [depositor-2] Deposit 10000.00 to SAV2001, balance: 130000.00
  [depositor-1] Deposit 10000.00 to SAV2001, balance: 140000.00
  [withdrawer-1] Withdraw 15000.00 from SAV2001, balance: 125000.00
  [depositor-2] Deposit 10000.00 to SAV2001, balance: 135000.00
  [depositor-3] Deposit 10000.00 to SAV2001, balance: 145000.00
  [withdrawer-2] Withdraw 15000.00 from SAV2001, balance: 130000.00
  [depositor-2] Deposit 10000.00 to SAV2001, balance: 140000.00
  [depositor-3] Deposit 10000.00 to SAV2001, balance: 150000.00
  [withdrawer-1] Withdraw 15000.00 from SAV2001, balance: 135000.00
  [withdrawer-2] Withdraw 15000.00 from SAV2001, balance: 120000.00
  [depositor-3] Deposit 10000.00 to SAV2001, balance: 130000.00

Final balance: 130000.00 INR
Expected: 100000 + (9 * 10000) - (4 * 15000) = 130000.00 INR

The order of individual operations varies per run, but the final balance is always correct because the synchronized methods prevent race conditions.

What should a senior or principal engineer know?

At the senior level, you should understand the performance cost of threads and when to use thread pools, virtual threads, or reactive frameworks.

  • Thread cost: Each platform thread allocates about 1 MB of stack memory by default (-Xss). Creating 10,000 threads uses 10 GB of stack space. Use thread pools to reuse threads.
  • Thread dumps: Use jstack or Thread.getAllStackTraces() to capture thread dumps. Look for BLOCKED threads to diagnose deadlocks.
  • Daemon threads: A daemon thread (thread.setDaemon(true)) does not prevent JVM shutdown. Use daemon threads for background tasks like cache cleanup. The JVM exits when only daemon threads remain.
  • Thread priority: Java thread priority (1 to 10) is a hint to the OS scheduler. On most systems, it has little effect. Do not rely on priority for correctness.
  • Pinning (virtual threads): A virtual thread running inside a synchronized block pins its carrier thread, blocking the carrier from serving other virtual threads. Use ReentrantLock instead of synchronized in virtual-thread code.
  • Structured concurrency (Java 25 preview): StructuredTaskScope groups related tasks and ensures they are all completed or cancelled together, preventing thread leaks.
JAVA
package com.bank.concurrency;

import java.util.Map;

public class SeniorThreadKnowledgeDemo {
    public static void main(String[] args) {
        // Thread dump: see all running threads
        System.out.println("=== Active Threads ===");
        Map<Thread, StackTraceElement[]> allThreads = Thread.getAllStackTraces();
        for (Thread t : allThreads.keySet()) {
            System.out.println("  " + t.getName()
                + " [" + t.getState() + "]" 
                + (t.isDaemon() ? " (daemon)" : ""));
        }
        System.out.println("Total threads: " + allThreads.size());
        System.out.println();

        // Daemon thread example
        Thread cacheCleanup = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(60_000);
                    System.out.println("Cache cleanup tick");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }, "cache-cleanup");
        cacheCleanup.setDaemon(true);
        cacheCleanup.start();
        System.out.println("Daemon thread started: " + cacheCleanup.getName());
        System.out.println("  isDaemon: " + cacheCleanup.isDaemon());
        System.out.println("  (JVM will exit even if this thread is still running)");
        System.out.println();

        System.out.println("=== Senior/Principal Checklist ===");
        System.out.println("1. Each platform thread costs ~1 MB stack. Use thread pools.");
        System.out.println("2. Use jstack or Thread.getAllStackTraces() for thread dumps.");
        System.out.println("3. Daemon threads do not block JVM shutdown.");
        System.out.println("4. Virtual threads: avoid synchronized, use ReentrantLock.");
        System.out.println("5. Structured concurrency (Java 25 preview) prevents thread leaks.");
        System.out.println("6. Monitor thread states with JMX ThreadMXBean.");
    }
}
TEXT
Expected output:
=== Active Threads ===
  main [RUNNABLE]
  Reference Handler [RUNNABLE] (daemon)
  Finalizer [WAITING] (daemon)
  Signal Dispatcher [RUNNABLE] (daemon)
  Common-Cleaner [TIMED_WAITING] (daemon)
Total threads: 5

Daemon thread started: cache-cleanup
  isDaemon: true
  (JVM will exit even if this thread is still running)

=== Senior/Principal Checklist ===
1. Each platform thread costs ~1 MB stack. Use thread pools.
2. Use jstack or Thread.getAllStackTraces() for thread dumps.
3. Daemon threads do not block JVM shutdown.
4. Virtual threads: avoid synchronized, use ReentrantLock.
5. Structured concurrency (Java 25 preview) prevents thread leaks.
6. Monitor thread states with JMX ThreadMXBean.

What are common interview follow-up questions?

  • What is the difference between start() and run()? (start() creates a new OS thread and calls run() in that thread. run() executes in the calling thread, no new thread is created.)
  • Can you call start() twice on the same Thread? (No. The second call throws IllegalThreadStateException. A thread can only be started once.)
  • What is the difference between sleep() and wait()? (sleep() pauses the current thread for a duration but does not release any lock. wait() releases the monitor lock and waits for notify() or notifyAll().)
  • What is a race condition? (When two or more threads access shared mutable data without synchronization, and the outcome depends on the order of thread execution.)
  • What is a deadlock? (When two threads each hold a lock the other needs, so both wait forever. Thread A holds lock 1 and waits for lock 2. Thread B holds lock 2 and waits for lock 1.)
  • How many threads should you create? (For CPU-bound work: number of CPU cores. For IO-bound work: more threads are acceptable because they spend time waiting. Virtual threads remove this sizing concern for IO-bound tasks.)
  • What is the difference between notify() and notifyAll()? (notify() wakes one waiting thread (chosen by the JVM, not predictable). notifyAll() wakes all waiting threads, and they compete for the lock.)

Visual Overview

DIAGRAM
 Thread Lifecycle (States)
 ==========================

         new Thread()
              │
              ▼
         ┌────────┐
         │  NEW   │
         └───┬────┘
             │ start()
             ▼
         ┌───────────┐
         │ RUNNABLE  │ ◄─────────────────────┐
         │ (running  │                       │
         │  or ready)│                       │
         └─┬──┬──┬──┘                       │
           │  │  │                           │
   wait()  │  │  │ sleep(ms)        lock     │
   join()  │  │  │ wait(ms)       acquired   │
           │  │  │ join(ms)                  │
           ▼  │  ▼                           │
    ┌─────────┐ ┌──────────────┐   ┌────────┴──┐
    │ WAITING │ │TIMED_WAITING │   │  BLOCKED  │
    └────┬────┘ └──────┬───────┘   │(waiting   │
         │             │           │ for lock) │
         │ notify()    │ timeout   └───────────┘
         │ notifyAll() │ expired
         └──────┬──────┘
                │
                ▼
           RUNNABLE
                │
                │ run() completes
                ▼
         ┌────────────┐
         │ TERMINATED │
         └────────────┘


 Process vs Thread Memory
 =========================

 ┌─────────────────────── Process ───────────────────────┐
 │                                                       │
 │  ┌───────────────────────────────────────────────┐    │
 │  │              Shared Heap Memory                │    │
 │  │  (Objects, Arrays, Static Fields)              │    │
 │  └───────────────────────────────────────────────┘    │
 │                                                       │
 │  ┌──────────┐  ┌──────────┐  ┌──────────┐            │
 │  │ Thread 1 │  │ Thread 2 │  │ Thread 3 │            │
 │  │  Stack   │  │  Stack   │  │  Stack   │            │
 │  │ (local   │  │ (local   │  │ (local   │            │
 │  │  vars)   │  │  vars)   │  │  vars)   │            │
 │  └──────────┘  └──────────┘  └──────────┘            │
 │                                                       │
 │  ┌───────────────────────────────────────────────┐    │
 │  │              Code Segment (shared)             │    │
 │  └───────────────────────────────────────────────┘    │
 └───────────────────────────────────────────────────────┘


 Context Switching
 ==================

 CPU Core 0:
 ┌──────────┐      ┌──────────┐      ┌──────────┐
 │ Thread A │ save │ Thread B │ save │ Thread A │
 │ running  │─────►│ running  │─────►│ running  │
 └──────────┘  ▲   └──────────┘  ▲   └──────────┘
               │                 │
         context switch    context switch
         (~1-10 us)        (~1-10 us)

Key Takeaway

A process is an independent running program with its own memory, and a thread is a lightweight unit of execution that shares memory with other threads in the same process. In a banking application, the account service and payment service run as separate processes (separate JVMs), while hundreds of concurrent customer requests are handled by threads within each process. Threads share heap memory, which makes communication fast but requires synchronization to prevent data corruption.

Java provides multiple ways to create threads: extending Thread, implementing Runnable, or implementing Callable for tasks that return results. In modern code, Runnable with lambda expressions is the standard approach because it separates the task logic from the thread mechanism and works with thread pools. Every platform thread maps to an OS thread, costs about 1 MB of stack memory, and is scheduled by the OS. Virtual threads (Java 21+) are managed by the JVM, cost about 1 KB each, and allow millions of concurrent threads for IO-bound workloads like database queries and HTTP calls.

In our National Bank of India transaction processor project, we built a thread-safe BankAccount with synchronized methods and ran five threads (three depositors, two withdrawers) concurrently. The synchronized keyword ensures that only one thread modifies the balance at a time, so the final balance is always correct regardless of thread interleaving. The key lesson is that shared mutable state requires synchronization, whether through synchronized blocks, Locks, or atomic variables.

Context switching is the OS mechanism that shares CPU cores among threads. For CPU-bound work, the optimal thread count equals the number of CPU cores. More threads cause excessive context switching and slow things down. For IO-bound work, threads spend most of their time waiting, so more threads improve throughput. Virtual threads eliminate the thread-count sizing problem for IO-bound workloads because they are so cheap that you can create one per task.

At the senior level, use thread pools to reuse threads, use jstack for thread dumps to diagnose deadlocks, and prefer ReentrantLock over synchronized in virtual-thread code to avoid carrier-thread pinning. At the principal level, adopt structured concurrency (Java 25 preview) to prevent thread leaks, and design thread models that match your workload: thread pools for CPU-bound, virtual threads for IO-bound.

Remember one sentence: a thread is a lightweight execution path within a process that shares heap memory with other threads, requires synchronization for shared mutable state, and is scheduled by the OS (platform threads) or the JVM (virtual threads).

---

Share
Use ← → arrow keys to navigate