Thread safety of instance methods that have local variables only

后端 未结 1 1455
一生所求
一生所求 2021-01-20 02:11

Generally, does simultaneously calling instance methods that use local variables only have bearing on thread safety?

Here\'s a short example. Multiple threads will c

相关标签:
1条回答
  • 2021-01-20 02:33

    When you call a method then local variable resides in the stack of individual call, so you don't need to worry about the local variables in case of Multi-Threading as well, but it can create issue if same File is passed as argument.

    Read Why are local variables thread safe in Java

    When you create a thread it will have its own stack created. Two threads will have two stacks and one thread never shares its stack with other thread.

    enter image description here

    Local variables are always thread safe. Keep in mind though, that the object a local variable points to, may not be so. If the object was instantiated inside the method, and never escapes, there will be no problem.

    On the other hand, a local variable pointing to some shared object, may still cause problems. Just because you assign a shared object to a local reference, does not mean that object automatically becomes thread safe.


    See JavaRanch - Thread safe and local variable.

    If the local variable is a primative variable, then yes, it is thread safe. If the local variable is a reference that is pointing to a locally created object, then yes, it should be thread safe (assuming the statics are thread safe).

    If the local variable is a reference that is pointing to an externally created object, then it is thread safe, if and only if the object can be used safely in a threaded fashion.

    0 讨论(0)
提交回复
热议问题