Escape analysis in English for escape analyses. In the principle of computer language compiler optimization, escape analysis refers to the method of analyzing pointer dynamic range, which is associated with pointer analysis and shape analysis of compiler optimization principle. When a variable (or object) is allocated in a method, its pointer may be returned or globally referenced, which is referred to by other procedures or threads, which is called a pointer (or reference) escape (escape).
In the Java Concurrency Programming book There is an example listing 3-7 referring to this escape. I didn't think about it at first. The main problem with discovering code is that an anonymous class was created in the constructor, and then the anonymous class was published.
Java code
- Import java.util.*;
- Public class Thisescape {
- private final int num;
- Public Thisescape (EventSource source) {
- Source.registerlistener (
- New EventListener () {
- public void OnEvent (Event e) {
- DoSomething (e);
- }
- });
- num = 42;
- }
- private void dosomething (Event e) {
- if (num! = ) {
- System.out.println ("Race condition detected");
- }
- }
- }
If this code is compiled, then Jd-gui can see DoSomething (e); It will become
ThisEscape.this.doSomething (e); This should be the standard way for the Java inner class to call the external class-the name of the external classes. This. Method name
If we dig further, we know that Thisescape will have two class files after compiling. One is Thisescape.class, the other one will be thisescape$1.class to this anonymous class.
Their contents are almost like this.
Java code
- Public class Thisescape {
- private final int num;
- Public Thisescape (EventSource source) {
- Source.registerlistener (new <strong><span style="color: #ff0000;" >thisescape$1</span></strong> (this));
- num = 42;
- }
- private void dosomething (Event e) {
- if (num! = )
- System.out.println (
- "Race condition detected");
- }
- static void access$(thisescape _this, event event) {
- _this.dosomething (event);
- }
- }
Java code
- Class thisescape$1 implements EventListener {
- final thisescape this$0;
- thisescape$1 (<span style="color: #ff0000;" >thisescape thisescape</span>) {
- this$0 = thisescape;
- super ();
- }
- public void OnEvent (Event e) {
- thisescape.access$(this$0, E);
- }
- }
Thus, if new thisescape$1(this) is executed in another thread, it may cause Num to escape the this to have not yet executed num = 42; Race condition detected will be displayed in the console at intervals.
Go Escape analysis of Java memory objects