内存地址存储在Java中的哪个位置

And*_*897 2 java jvm memory-management

Java中存储的内存地址在哪里?我想要了解的是如何存储以下内容.我已经知道堆栈和堆栈之间的区别,但是试图挖掘比这更深的层.

int i = 5;
Run Code Online (Sandbox Code Playgroud)

i单独存储还是单独5存储,然后建立映射?

类似地,我们说对于32位版本,最多可以有4 GB RAM(实际上要少得多),所有这些内存块的内存地址都存储在哪里?

T.J*_*der 5

我想要了解的是如何存储以下内容.

这取决于它在哪里int i = 5;:

局部变量

如果它在一个方法中并且因此i是一个局部变量,那么它5被存储为堆栈中的本地(i不是"存储"在任何地方,字节码生成器只记得堆栈中的i位置).字节码具有与局部变量交互的特定指令,包括一些非常有效的专用无争论版本,例如从"局部变量0" iload_0加载int.(那些经过iload_3,然后有一个版本采取arg,iload然后是索引.)

考虑这个课程:

public class Example {

    public static final void main(String[] args) {
        int i = 5;

        System.out.println(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是字节码(你可以通过编译然后再做javap -c Example),右边的注释:

public class Example {
  // ...omitted constructor stuff...

  public static final void main(java.lang.String[]);
    Code:
      // The `int i = 5;` line:
       0: iconst_5               // Load the constant 5 onto the stack
       1: istore_1               // Store it in local variable 1

      // The `System.out.println(i);` line:
       2: getstatic     #2       // Get the static field java/lang/System.out:Ljava/io/PrintStream onto the stack
       5: iload_1                // Load int variable 1 on the stack
       6: invokevirtual #3       // Call java/io/PrintStream.println, which gets
                                 // the stream and what to write from the stack
       9: return
}
Run Code Online (Sandbox Code Playgroud)

请注意堆栈的两种不同用途:"locals"位于堆栈的一部分,该方法为本地分配了自己(因为它事先知道有多少),然后是动态部分,然后是它用于将信息传递到方法等.

实例字段

如果它在类定义中并因此i是类的实例字段,i则是Java为实例保留(在堆栈或堆上,有时在它们之间移动)的结构的一部分.

字节码并没有真正流下了很多关于这种光的,但考虑到这个类:

public class Example {

    int i = 5;

    public static final void main(String[] args) {

        Example ex = new Example();
        System.out.println(ex.i);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是字节码:

public class Example {
  // Here's the instance field
  int i;

  // ...omitted the constructor stuff...

  public static final void main(java.lang.String[]);
    Code:
      // Create our Example instance and save it in a local variable
       0: new           #3
       3: dup
       4: invokespecial #4
       7: astore_1

      // The `System.out.println(ex.i)` line:
       8: getstatic     #5     // Get the java/lang/System.out:Ljava/io/PrintStream field
      11: aload_1              // Get `ex` onto the stack
      12: getfield      #2     // Get the value of field `i` onto the stack from the instance we just put on the stack (pops the instance off)
      15: invokevirtual #6     // Call java/io/PrintStream.println, which
                               // again gets the stream to write to and
                               // what to write from the stack
      18: return
}
Run Code Online (Sandbox Code Playgroud)