首先,什么是this逃逸?

this逃逸是指类构造函数在返回实例之前,线程便持有该对象的引用。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

常发生于在构造函数中启动线程或注册监听器。

eg:

public class ThisEscape {
    private String value = "";

    public ThisEscape() {
        new Thread(new TestDemo()).start();
        this.value = "this escape";
    }

    public class TestDemo implements Runnable {
        @Override
        public void run() {
            /**
             * 这里通过ThisEscape.this调用外围类(即ThisEscape是TestDemo的外围类)的对象
        * 但此时外围类对象可能还没有构造完成, * 所以会发生this逃逸现象
*/ System.out.println(ThisEscape.this.value); } } }

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄