When learning multithreading in Java, it’s important to first understand how processes and threads work, and how the JVM allocates memory to manage them.
🔹 Process vs Thread
Process
A process is an instance of a program in execution.
Each process has its own memory space (code, data, heap, stack).
The Operating System (OS) allocates resources like CPU time, memory, and file handles to each process.
Example: Running java Main starts the JVM as a process.
Thread
A thread is the smallest unit of execution within a process (sometimes called a lightweight process).
A process can contain multiple threads.
When a process starts, it begins with one main thread.
Threads inside a process run concurrently, improving performance.
Each thread has its own stack, program counter, and name, but shares the process’s code, data, and heap.
🧑💻 Example: Current Thread in Java
public class Main {
public static void main(String[] args) {
System.out.println("Running current thread: " + Thread.currentThread().getName());
}
}
Output:
Running current thread: main
👉 By default, the JVM starts your program with the main thread.
🧩 JVM Instance & Memory Allocation
When you run a Java program, here’s what happens step by step:
Step 1: Compilation
javac Main.java
Source code (.java) → Compiled into bytecode (.class)
Bytecode is platform-independent, runs on the JVM.
Step 2: Execution
java Main
OS creates a process for the JVM.
Inside this process, a JVM instance is created.
JVM uses an interpreter/JIT compiler to convert bytecode → machine code.
🗂 JVM Memory Segments
_ Code Segment (Method Area)_
Stores compiled bytecode/machine code.
Shared across all threads.
_ Data Segment_
Stores global and static variables.
Shared by all threads → needs synchronization.
_ Heap Memory_
Stores objects created with new.
Shared across all threads.
Stack Memory (per thread)
Each thread has its own stack.
Stores method calls, local variables, and references.
_ Registers (per thread)_
CPU registers store the program counter.
Used during context switching between threads.
⚙️ Who Executes Threads?
The OS scheduler or JVM thread scheduler is responsible for:
Loading thread registers into the CPU.
Managing execution order.
Handling context switching.
Ensuring efficient parallel execution.
✅ Summary
A process is a running program with its own memory.
A thread is the smallest execution unit inside a process.
JVM memory is divided into code, data, heap, stack, and registers.
Threads share code, data, and heap, but each has its own stack and registers.
This structure allows efficient execution and multithreading in Java.
🚀 With this foundation, you’re ready to dive deeper into Java concurrency APIs, thread pools, and synchronization techniques!
Top comments (0)