What happens when two threads call the same static method at the same time?
java, multithreading, static, synchronized
Solution
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:
- Longs are not guaranteed to be set atomically, so they might be 'torn' (Spec)
- `++` 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 repeated
- The return of n might be stale
But 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.
Problem
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?