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.
When I call test()
in each thread, can I guarantee that test()
is thread safe?
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!
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.
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.
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.
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
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