Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables and thread safety

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.

like image 712
Jonathan. Avatar asked Apr 28 '15 16:04

Jonathan.


People also ask

Why are local variables thread safe in Java?

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.

Are local variables thread safe in Python?

Local variables and parameters are always thread-safe. Instance variables, class variables, and global variables may not be thread-safe (but they might be).

Are private variables thread safe?

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.


1 Answers

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.)

like image 144
Jon Skeet Avatar answered Oct 04 '22 03:10

Jon Skeet