Think of methods like defining functionality. When two threads start the same method, they are in no way connected to each other. Each of them will create its own version of each local variable and will not be able to interact with each other in any way.
If the variables are not local (for example, instance variables defined outside the method at the class level), then they are bound to the instance (and not to a single run of the method). In this case, two threads working on the same method see one variable, and this is not thread safe.
Consider these two cases:
public class NotThreadsafe { int x = 0; public int incrementX() { x++; return x; } } public class Threadsafe { public int getTwoTimesTwo() { int x = 1; x++; return x*x; } }
In the first case, two threads running in the same instance of NotThreadsafe will see the same x. This can be dangerous because threads are trying to change x! In the second case, two threads running on the same Threadsafe instance will see completely different variables and cannot affect each other.
Cory Kendall Oct 10 '12 at 18:25 2012-10-10 18:25
source share