jvm学习笔记:程序计数器

314 阅读2分钟

程序计数器(PC Register)

The Java Virtual Machine can support many threads of execution at once (JLS §17). Each Java Virtual Machine thread has its own pc (program counter) register. At any point, each Java Virtual Machine thread is executing the code of a single method, namely the current method (§2.6) for that thread. If that method is not native, the pc register contains the address of the Java Virtual Machine instruction currently being executed. If the method currently being executed by the thread is native, the value of the Java Virtual Machine's pc register is undefined. The Java Virtual Machine's pc register is wide enough to hold a returnAddress or a native pointer on the specific platform.

JVM中的程序计数寄存器(Programe Counter Register)类似于CPU中的寄存器,CPU寄存器负责存储指令相关的现场信息,CPU只有把数据存放在寄存器才能正常执行指令。

JVM中的寄存器不是物理上的寄存器而是对物理寄存器的抽象模拟。

程序计数器也称为为程序钩子

作用

PC寄存器用于存储指向下一条指令的地址

任何时间一个线程都只有一个方法在执行,计数器会存储当前线程正在执行的方法的JVM指令地址

特点

  • 很小的内存区域,读取速度很快(与CPU的寄存器类似)
  • 每个线程独有,与线程的生命周期相同
  • 负责记录每个线程当前执行到的位置
  • 如果执行本地方法,计数器会存储undefined
  • JVM中唯一一个没有Out Of Memory Error的区域,也没有用到垃圾回收

常见面试题

Q:为什么要使用PC寄存器记录下一条指令的地址?

A:因为程序执行时CPU会不断切换线程执行,线程切换回来后必须要知道接下来要执行哪一条指令。

Q:PC寄存器为什么要线程私有

A:CPU不断在线程之间切换,如果共用PC寄存器,比如线程1没执行完切换到线程2,线程2就会覆盖掉线程1将要执行的指令地址