Created
November 29, 2011 14:16
-
-
Save khotyn/1404939 to your computer and use it in GitHub Desktop.
This pointer escape while creating a new Object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result:
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: