-1

I am learning Java multi threading and I read the following statement :

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. Just because you assign a shared object to a local reference, does not mean that object automatically becomes thread safe.

public class SimpleHttpServlet extends HttpServlet {

 

  protected void Test() {

    // How can `object' become not thread safe
    SomeClass object= new SomeClass ();

  }
}

In this example how can object become not thread safe ?

Can you please explain with an example a scenario where local variable can be not thread safe and why ?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
alex
  • 71
  • 1
  • 5
  • 2
    "If the object was instantiated inside the method, and never escapes, there will be no problem." – Smutje Oct 07 '20 at 09:50
  • 1
    Imagine you declare a local variable, but to give it a value you do something like `SomeClass object = SomeOtherClass.getValue()`. Is what `getValue` returns *guaranteed* to not be modified in another thread? There you have an example where `object` has become non-thread safe. – Federico klez Culloca Oct 07 '20 at 09:52

1 Answers1

1

As the quoted text itself says object itself (i.e. the local variable) is thread safe.

You can rely on the fact that no outside factor (i.e. no other thread) changes what this variable references.

However the object that object references (the one created by new SomeClass()) could be manipulated by other threads if a reference to it somehow escapes. For example if you did something like myGlobalList.add(object) and myGlobalList was accessible to other threads, then another thread could get the object back and call setFoo on it, which might have unexpected effects on your code.

That "other threads being able to access the object" is called "escaping", i.e. your object escapes.

In your overly simplified example this doesn't happen. You don't store a reference to that object anywhere else, so it will of course stay thread safe.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614