Reputation: 69
In following example how many stacks gets created ?
public class Test {
public static void main(String [] args){
Test test = new Test();
test.callMe();
}
public void callMe(){
System.out.println("Call Me");
callMe2();
}
public void callMe2(){
System.out.println("Call Me2");
}
}
if there are two thread accessing main method at the same time, how many stacks gets created ? Isn't stack shared between methods ?
Upvotes: 3
Views: 1569
Reputation: 613592
If there was a new local variable frame for each method call then you would not need a stack. You could do it all with heap memory. In reality, for performance reasons all practical implementations will use a stack and have a one to one correspondence between stacks and threads.
Upvotes: 1
Reputation: 23248
how many stacks gets created ? Isn't stack shared between methods ?
Just to clarify, stack is an implementation detail and are not created in Java. Also, methods are language level abstraction whereas the stack is part of your runtime. The correct answer to this question depends on a lot of things like OS, the machine architecture etc. and is not covered in the JLS.
Upvotes: 1
Reputation: 533880
Each thread has a stack, each method call uses a new area of that stack. This means if a method calls itself, it will have a new set of local variables.
Upvotes: 8