With normal instance methods, local variables are thread safe.
If I have the following in a static method:
int i = 0;
i += 3;
Would this be thread-safe? Is there any catch?
Also, what exactly does it mean when each variable has its own stack? Does that mean its own stacktrace?
Thanks
If the lines you posted are inside the method, then there’s no reason why it shouldn’t be threadsafe. The threads aren’t interacting in any way – each thread sees a different
i.The catch comes if you try to share the value of i between threads, for example by making
ia static field. Then it’s possible to get a race condition where you get different results depending on timing.Regarding your second question, each thread has its own stack, not each variable.