简体   繁体   中英

Java heap and stack memory allocation

class Person{
          private String name;
          public Person(){
          }

          public Person(String name){
              this.name=name;
          }

          public static void main(String[] arg)
          {
                Person per= new Person("Andy");
          }
    }

per is a local variable, where will it be stored, on the heap or the stack?

Objects are always stored in the heap . However, the reference to per will be stored in the local variable array , which is stored in the frame created for main(String[]) , which is stored in the stack .

For more information, see: The Structure of the Java Virtual Machine .

Edit: I've learnt that JVMs are actually able to allocate objects on the stack by performing escape analysis . Better yet, a technique called scalar replacement can be applied, where the object allocation is omitted, and the object's fields are treated as local variables. It is possible for the variables to be allocated on machine registers.

Escape analysis by stack allocation has been implemented by HotSpot VMs since Java 6u14. It has been enabled by default since Java 6u23. For an object to be allocated on the stack, it must not escape the executing thread, the method body or be passed as an argument to another method.

On the heap. Any time you use new to create an object, it is allocated on the heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM