What happens when two threads call the same static method at the same time?

Ernestas Gruodis picture Ernestas Gruodis · Feb 18, 2014 · Viewed 14.8k times · Source

What happens when two threads call the same static method at the same time? For example:

public static String someMethod(){

    //some logic, can take about 1 second to process

    return new String(result);
}

First thread calls someMethod() now. Second thread calls someMethod() 0.5 seconds from now (first thread still processing the data).

I know that someMethod() can be synchronized. But what will happen if it's not synchronized?

Answer

When a method is called, the JVM creates a stack frame for the call in the executing thread. This frame contains all of the local variables declared in the method. In the case of any method, static or otherwise, that doesn't access fields, each execution proceeds completely independently on each thread. If the method uses parameters in its calculation, these parameters are also located in the stack frame, and multiple calls don't interfere with each other.