Daehee Han Daehee Han - 9 months ago 49
Java Question

Local variables in static method and thread safety

I have a question about variable scope.

For example:

class A {
private static void test() {
// do something with local variables

Now I make two threads, and create one instance of
for each thread.

  1. When I call
    in each thread, can I guarantee that
    is thread safe?

  2. Where are the local varibles in
    stored? Each threads' stack? Heap space?

P.S. I know that static is totally pointless in this case. I found it in our legacy code; I just wanna make sure what I know!

Answer Source

Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.

Local references to objects are a bit different. The reference itself is not shared. The object referenced however, is not stored in each threads's local stack. All objects are stored in the shared heap. If an object created locally never escapes the method it was created in, it is thread safe. In fact you can also pass it on to other methods and objects as long as none of these methods or objects make the passed object available to other threads.

Object members are stored on the heap along with the object. Therefore, if two threads call a method on the same object instance and this method updates object members, the method is not thread safe.

Thread safety check: If a resource is created, used and disposed within the control of the same thread, and never escapes the control of this thread,the use of that resource is thread safe.

From: http://tutorials.jenkov.com/java-concurrency/thread-safety.html