Program Counter

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

TL;DR

  • The PC (Program Counter) Register is a tiny, thread-local memory space in the JVM.
  • It holds the exact memory address of the JVM instruction that is currently being executed by the thread.
  • Every single thread has its own private PC Register.

Concept

The CPU executes instructions sequentially. However, in a multithreaded environment, the OS constantly performs Context Switching.
Thread A might execute lines 1, 2, and 3, and then suddenly the OS pauses Thread A and gives the CPU to Thread B.

When Thread A is eventually resumed, how does it know where it left off?
The PC Register acts as a bookmark. Before Thread A is paused, its PC Register is updated to point to line 4. When it resumes, the JVM looks at the PC Register and instantly knows to resume execution at line 4.

Examples

public class ProgramCounterExample {
    public static void main(String[] args) {
        
        // Imagine bytecode instructions:
        int a = 5;  // Instruction 1 (PC points here)
        int b = 10; // Instruction 2 (PC updates to here)
        
        // Thread gets paused by the OS right now!
        // The PC Register safely stores the address for Instruction 3.
        
        int sum = a + b; // Instruction 3 
        System.out.println(sum);
    }
}

Interview Questions

Q: Does the PC Register track native methods?
A: No. If a thread calls a standard Java method, the PC Register holds the address of the current bytecode instruction. However, if the thread calls a Native Method (a method written in C or C++), the JVM has no idea how to track the internal instructions of compiled C code. Therefore, during the execution of a native method, the PC Register value is completely undefined (or empty).

Q: Can the PC Register throw an OutOfMemoryError?
A: No. The PC Register is the only Runtime Data Area in the JVM specification that does not throw an OutOfMemoryError. It is extremely tiny—it only needs enough memory to hold a single memory address (a pointer/reference), which is a fixed size (usually 64 bits). It never grows dynamically.