3

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

Here's a short example. Multiple threads will call a();.

public class A {
    public boolean a(File file) throws Exception {
        boolean t = true;
        FileInputStream fin = null;
        BufferedInputStream bin = null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            while(bin.read() > 0) {}
            return t; 
        finally {
            try {
                if (in != null) in.close();
            } catch (IOException e) {}
            try {
                if (fin != null) fin.close();
            } catch (IOException e) {}
        }
    }
}
Unihedron
  • 10,902
  • 13
  • 62
  • 72
damat-perdigannat
  • 5,780
  • 1
  • 17
  • 33

1 Answers1

14

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.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • 2
    +1 for addressing the issues related to object referencing. Good point. – Ankur Shanbhag Aug 15 '14 at 04:53
  • 2
    Local variables that point to objects that are created in the thread and never escape can still cause problems. When they directly or indirectly refer to shared resources (through static fields, through ThreadLocal variables, or one of the many other mechanisms provided by the API or third party libraries) they can cause concurrency issues as well. – Erwin Bolwidt Aug 15 '14 at 05:00