Reputation: 8787
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?
Upvotes: 25
Views: 20107
Reputation: 22446
The fact the method is static is irrelevant. They question should be what state variables are being manipulated by the code in question.
Upvotes: 5
Reputation: 2143
It depends on whether your method changes outside state.
static long i = 0l;
public static String someMethod(){
String accm = "";
for(;i < Integer.MAX_VALUE*20/*Just to make sure word tearing occurs*/; i++)
accm += i
return accm;
}
Will cause problems:
++
is not an atomic operation. It is exactly the same as {int n = i; i = i + 1; return n}
i = i + 1
is also not atomic, if it changes in the middle, some values will be repeatedBut if i
is a local variable, there will be no problems. As long as any outside state is guaranteed to be immutable while it is being read, there can never be any problems.
Upvotes: 16
Reputation: 8219
If the two statements are executed in separate threads, there's no guarantee that the first thread changes will be visible to the second thread unless you establish a happens-before relationship between these two statements by synchronizing someMethod()
using a given synchronization strategy. In other words, your logic can give unexpected and unpredictable results if you are writing to the same variable(s) and then reading from two threads simultaneously.
Upvotes: 0
Reputation: 77186
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.
Upvotes: 34