简体   繁体   中英

Java memory (Stack) allocation for local variables

I am learning java and right now i am stuck at memory allocation of object's and local variables. can any one illustrate or clear some of my doubts??

  1. I read about Heap and Stack Memory for Object's instance Variable's and Local Variable's. I have question whether a new STACK is being created for each method?? or for each class of a single stack is used by a whole class??
  2. I had read that ONE STACK is being created by every thread What is means

Thanks Mahaveer

Every thread has it's own stack .

  • Whenever you use new , an object is created on the heap .
  • Local variables are stored on the stack. That includes primitives (such as int ) and the references to any objects created. The actual objects themselves aren't created on the stack, as I mentioned when you use new they'll be created on the heap.

I have question that weather a new STACK is being created for each method??

The same stack is being used when a method is called. A method will create it's own little section on the stack called a "stack frame" that's used to hold it's local variables.

It's just like a stack of plates, when a method is called a plate is added to the top of the stack (a stack frame ), and when that method ends the plate is removed from the stack. All of that method's local variables will be destroyed with it, but the actual objects created with new won't.

The JVM's garbage collector will look after destroying objects on the heap (the one's created with new ) when it sees you no longer need them.

  • Each thread has a private stack.
  • Each method has a private stack frame within that thread's stack.

Stacks are associated with thread in a one-to-one mapping. Stacks are absolutely not associated with methods and classes.

The way to reason about all this is that the local variables of a method are private to each invocation of that method.

当然,java垃圾收集器总是处理堆,当它有机会被执行时,所以它只查找孤立对象并将它们擦除,这就是为什么java中的NEW关键字总是在堆内存上创建新对象的原因。

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