Process vs Thread

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • A Process is an independent program in execution with its own memory space (e.g., Google Chrome, the JVM).
  • A Thread is a subset of a process; multiple threads exist within a single process.
  • Threads share the memory (Heap) of the process they belong to, making communication faster but synchronization harder.

Concept

Process

When you double-click a Java application, the Operating System allocates a large chunk of memory, assigns resources, and launches the JVM. This entire entity is a Process. Processes are isolated. If a process crashes, it doesn’t crash the entire computer. Because they are isolated, processes communicate via expensive mechanisms (IPC, sockets, pipes).

Thread

Inside that JVM Process, the application executes code. This execution path is a Thread. A single process can spin up hundreds of threads. Because these threads live in the exact same memory space (the JVM Heap), Thread A can instantly access a variable created by Thread B without any heavy OS intervention. However, this shared memory is exactly what causes Concurrency Bugs (like Race Conditions).

Examples

public class ProcessVsThread {
    
    // Shared Memory (Heap)
    // All threads in this JVM process can access this variable
    public static int sharedCounter = 0;
    
    public static void main(String[] args) {
        
        // Thread 1
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                sharedCounter++; // Accessing shared memory
            }
        });
        
        // Thread 2
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                sharedCounter++; // Accessing shared memory
            }
        });
        
        t1.start();
        t2.start();
        
        // Note: Because they share memory, sharedCounter will suffer from 
        // a Race Condition unless properly synchronized!
    }
}

Interview Questions

Q: Which is more “expensive” to create: a Process or a Thread?
A: A Process is vastly more expensive to create. Creating a process requires the Operating System to allocate isolated virtual memory spaces, file descriptors, and system resources. Creating a Thread is considered “lightweight” because it simply requires allocating a small execution stack within the already existing memory space of the process.

Q: What is “Context Switching”?
A: A CPU core can only execute one thing at a exact millisecond. To create the illusion that 100 threads are running simultaneously, the OS rapidly pauses one thread, saves its state, and resumes another thread. This rapid pausing and resuming is called Context Switching. It is computationally expensive. If you spawn 10,000 threads, the CPU will spend all its time context switching instead of doing actual work.