In Java if you have the following method:
public int foo(int n) {
int i=n;
i = i+1; i = i-1;
return i;
}
So in a sequential program the return value will always be the same as the input.
ie: j == foo(j)
However if you have multiple threads call foo, can you guarantee that j==foo(j)
?
I would say yes that it is guaranteed, because i
is a local variable, and each thread has its own stack so i
will be a different memory location for each thread.
I would say you couldn't guarantee that j==foo(j)
if i
is a instance variable:
private int i;
public int foo(int n) {
i=n;
i = i+1; i = i-1;
return i;
}
Because the threads can interleave and the value of i
can change half way through a thread executing the method, or one thread can increment i
, but before it gets chance to decrement it, another thread returns with it's input incremented twice and decremented only once.
In addition, it's important to realize that every thread, including the main thread, has its own private stack. Therefore, other threads do not share our local variables, which is what makes them thread-safe.
Local variables and parameters are always thread-safe. Instance variables, class variables, and global variables may not be thread-safe (but they might be).
They're only as safe as you make them, and there are many ways to make them unsafe. For example there's nothing safe about passing one instance variable to two other threads. There's nothing safe about two threads calling a method on your object which happens to reference an instance variable.
I would say yes that it is guaranteed, because i is a local variable, and each thread has its own stack so i will be a different memory location for each thread.
Exactly. Each call to foo
will be independent, because foo
isn't using any shared state.
I would say you couldn't guarantee that j==foo(j) if i is a instance variable
Correct again. Sounds like you've basically got the right idea. (Note that even "increment" and "decrement" aren't atomic operations, so if you've got multiple threads performing those operations, you end up in tricky situations. That's why AtomicInteger
exists.)
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