Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables in static method and thread safety

Tags:

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 A for each thread.

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

  2. Where are the local varibles in test() 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!

like image 789
Daehee Han Avatar asked Jul 18 '12 06:07

Daehee Han


People also ask

Can a static method use local variables?

Local variables in static methods are just local variables in a static method. They're not static, and they're not special in any way. Static variables are held in memory attached to the corresponding Class objects; any objects referenced by static reference variables just live in the regular heap.

Are local objects thread safe?

Local References 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.

Can threads access local variables?

So local variables and in the stack of the main thread and another thread will have their own stack so it is not possible that threads can share local variables.


1 Answers

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

like image 144
Erol Avatar answered Oct 26 '22 11:10

Erol