JVM PC(程序计数器 program counter)

The 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.

1. 抽象的理解

  • 从官方文档上来看,我们可以确定PC的几个性质:
    1. 每个线程都有一个
    1. 线程私有
    1. PC一般会指示当前执行的字节码地址
    1. PC的大小足够放一个返回值地址的指针(a native pointer)
  • 从JVM内存的划分上来看, PC是线程私有的一块内存区域:
    JVM PC(程序计数器 program counter)_第1张图片

2. 具象的理解

PC里存的字节码地址是什么?

我们来找找指令的行号怎么来的,下面一步一步来操作

  1. 写一个java文件
//举个例子,注意包名,最好不要包名,不然javac,javap不方便
public class A{
    private volatile int aa = 0;
    public static void main(String[] args) {
        A a = new A();
        int aa = a.aa;
        System.out.println(aa);
    }
}
  1. javac编译为字节码class文件
  2. javap -c A.class > a.txt 用反汇编工具把字节码解析成方便查看的字节码指令
    JVM PC(程序计数器 program counter)_第2张图片
  • 这些行号就是当前指令的偏移量
  • 也就是PC记录的东西,字节码指令的偏移地址
  • 而native方法是不存在字节码一说的,所以执行native方法PC中的值是undefined(这里的PC是指JVM的PC)

你可能感兴趣的:(JVM学习)