Local Object Reference escaping
-
In terms of thread safety: How can it be determined an object escapes a method call, without using JVM escape analysis? ('Escaping' means that an object can be accessed after the method completes) A couple of examples on how an object can escape a method call: 1) The method returns the object that was locally created:
public MyObject someMethod(){
MyObject localObject = new MyObject();
return localObject();
}//Another thread can now mutate this object because it has a reference to it:
someMethod.changeSomething();-
One of the methods called with the LocalObject as parameter, stores the LocalObject instance in a way that allows access to it from other threads.
MyMember member; public void someMethod(){ LocalObject localObject = new LocalObject(); localObject.callMethod(); method2(localObject); } public void method2(LocalObject localObject){ localObject.setValue("value"); member = localObject; }
Does anyone know any more practical examples on how an object can escape a method call?
-
-
In terms of thread safety: How can it be determined an object escapes a method call, without using JVM escape analysis? ('Escaping' means that an object can be accessed after the method completes) A couple of examples on how an object can escape a method call: 1) The method returns the object that was locally created:
public MyObject someMethod(){
MyObject localObject = new MyObject();
return localObject();
}//Another thread can now mutate this object because it has a reference to it:
someMethod.changeSomething();-
One of the methods called with the LocalObject as parameter, stores the LocalObject instance in a way that allows access to it from other threads.
MyMember member; public void someMethod(){ LocalObject localObject = new LocalObject(); localObject.callMethod(); method2(localObject); } public void method2(LocalObject localObject){ localObject.setValue("value"); member = localObject; }
Does anyone know any more practical examples on how an object can escape a method call?
Neo10101 wrote:
//Another thread can now mutate this object because it has a reference to it:
No it can't. Not from that method. Thread 1 calls that method. That method create a brand spanking new object and returns it to the caller. Thread 2 calls that method. That method create a brand spanking new object and returns it to the caller. Neither object is the same. The calling sequence of the threads 1 and 2 are irrelevant (again in the context of this method only) each will still get a new object which is untouchable by the other thread.
Neo10101 wrote:
Does anyone know any more practical examples on how an object can escape a method call?
The method returns a data member of the class which is an object. So public MyObject getMyObject() { return myObject; }
-