Kabeer
Kabeer

Reputation: 69

stack per thread or per method call?

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

Answers (3)

David Heffernan
David Heffernan

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

Sanjay T. Sharma
Sanjay T. Sharma

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

Peter Lawrey
Peter Lawrey

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

Related Questions