Welcome to github.com/hsfxuebao/j… , hope to help you, if you feel ok, please click on the Star
From: www.cnblogs.com/xjwhaha/p/1…
1. An overview of the
- The Program Counter Register in the JVM is named after the CPU Register, which stores instruction related field information. The CPU can only run if it loads data into a register. That’s why some people call it a program register
- Instead of referring to a physical register in a broad sense, it might be more appropriate to translate it as a PC counter (or instruction counter) (also known as a program hook) and less likely to cause unnecessary misunderstanding. The PC register in the JVM is an abstract simulation of the physical PC register.
- It’s such a small amount of memory that you can barely remember it. It is also the fastest storage area.
- In the JVM specification, each thread has its own program counter, which is thread-private and whose lifetime is consistent with that of the thread.
- There is only one method executing on a thread at any one time, known as the current method (a thread corresponds to a stack, and when a method is called, the method is pushed onto the stack, and the method at the top of the stack is the method that the thread is running on). The program counter stores the JVM instruction address of the Java method being executed by the current thread; Or, if you are executing a native method, undefned.
- It is an indicator of program control flow, and basic functions such as branching, looping, jumping, exception handling, thread recovery, and so on rely on this counter. The bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to execute.
- It is the only area where the Java Virtual Machine specification does not specify any OutofMemoryError(memory overflow) cases.
Back to the top
2. The role
The PC register is used to store the address of the next instruction to be executed by a thread, and also the instruction code to be executed. The execution engine reads the next instruction and executes it.
The sample code
public class PCRegisterTest { public static void main(String[] args) { int i = 10; int j = 20; int k = i + j; String s = "abc"; System.out.println(i); System.out.println(k); }}Copy the code
A directive to decompile the main method
The number on the left represents the instruction address (instruction offset), which is the value that might be stored in the PC register, which the execution engine then reads and executes
Issues related to
Why design this program counter?
As mentioned above, each thread has a program counter that keeps track of which instruction is being executed by the current thread. Therefore, when the CPU has to switch between threads repeatedly, when it switches back, To know where to proceed, the JVM’s bytecode interpreter needs to change the value of the PC register to figure out what bytecode instruction to execute next