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.
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.)
See more on this question at Stackoverflow