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?
Many threads/callers can be calling the same static method at the same time. They don't wait on each other. If you wanted to limit the calls so they *couldn't* run in parallel, you'd need to add the word "synchronized" to the method. But by default, methods do what you want and there is no bottleneck.
Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.
Static Synchronized method is also a method of synchronizing a method in java such that no two threads can act simultaneously static upon the synchronized method. The only difference is by using Static Synchronized. We are attaining a class-level lock such that only one thread will operate on the method.
Since both the objects are different hence both synchronized static and non-static method will not block each other in case of multi-threading. Both the methods will execute simultaneously. Show activity on this post. Yes..
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With