Skip to content

Instantly share code, notes, and snippets.

@khotyn
Created November 29, 2011 14:16
Show Gist options
  • Save khotyn/1404939 to your computer and use it in GitHub Desktop.
Save khotyn/1404939 to your computer and use it in GitHub Desktop.
This pointer escape while creating a new Object
public class ThisEscape {
public static Escape escape;
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
try {
new ThisEscape().test();
} catch (InterruptedException e) {
// Pokemon exception handling!!
}
}
}).start();
TimeUnit.SECONDS.sleep(1);
System.out.println(escape.str);
System.out.println(escape.finalStr);
}
public void test() throws InterruptedException {
new Escape();
}
class Escape {
String str = "Normal String";
final String finalStr;
Escape() throws InterruptedException {
System.out.println("Constructor start.");
escape = this;
TimeUnit.SECONDS.sleep(2);
finalStr = "Hello, world!";
System.out.println("Constructor end.");
}
}
}
@khotyn
Copy link
Author

khotyn commented Nov 29, 2011

Result:

Constructor start.
Normal String
null
Constructor end.

It seems that the instance of a class has been initialized before executing the constructor. And still, you can get the final field of an instance of a class before it is properly constructed.
Let's see how final is defined in JMM:

The values for an object's final fields are set in its constructor. Assuming the object is constructed "correctly", once an object is constructed, the values assigned to the final fields in the constructor will be visible to all other threads without synchronization. In addition, the visible values for any other object or array referenced by those final fields will be at least as up-to-date as the final fields.
What does it mean for an object to be properly constructed? It simply means that no reference to the object being constructed is allowed to "escape" during construction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment