Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 559
Pawan Avatar asked Jun 18 '11 13:06

Pawan


1 Answers

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.

like image 102
someguy Avatar answered Nov 11 '22 05:11

someguy