Java Static vs Stack with Thread

As far as I know all the static variables and static methods will go on Static and all the methods, local variables and reference variable that declare in the method will go on Stack, but what about local variables and reference variables in a static method ? I guess they will be allocated on the Stack, but I am not sure how does it work.

For example:

 public static void A(){
      int x = 3;
      Point p = new Point();
 } 

Also I guess all the threads share Static as well as they share Heap, correct ?


You can think of local variables as always being allocated on the stack of the executing thread. I guess JIT compiler could optimise them into registers, but semantically they are indistinguishable from stack allocated variables. Their scope and lifetime is private to each invocation of a function.

You also ask about static variables (class variables) and the heap. Class variables are shared between threads in the sense that references to class variables all refer to the same variable no matter which thread is executing. And likewise for objects that reside on the heap.


I don't think there is something called Static memory area. If it's primitive type variable it will be allocated in Stack and if it's reference type then the object itself is allocated in Heap, but the variable referencing to the address where object has been placed will be allocated in Stack. But the only thing different for static variables is that they will be initialized first and it's done by JVM, so they will be allocated first in Stack, before any other variables.

You can find more information here: static allocation in java - heap, stack and permanent generation


Every definition is put on the stack in the current context. Essentially, a new context is pushed onto the stack every time you have { and it is popped out of the stack when you have } . Then all variables declared in a given context are added to the current context at the top of the stack. When the context is popped, all the definitions in contained are forgotten.

This is why this works:

public void method() {
    {
        int x = 0;
    }

    // x isn't defined here

    {
        int x = 0;  // This doesn't conflict with the previous declaration of x because we just created a new context and the other one was popped before.
    }
}
链接地址: http://www.djcxy.com/p/82866.html

上一篇: Java如何管理内存?

下一篇: Java静态与堆栈与线程