对象的不安全发布主要有:this逸出,在对象还未实例化完成时,就能被其他对象锁获取(发布)
this逸出
什么是this逸出
对于一个类C来说,“外部方法”指的是行为不完全由类C规定的方法,包括其他类定义的方法,以及类C中可以被改写的方法。当把类C的对象传递给某个外部方法时,相当于发布了该对象,此时如果C的实例未完成实例化,就称为类C的实例的this逸出。最常见的“外部方法”使用场景是在构造器中生成内部类实例。
1 // 定义一个事件监听的接口
2 public interface EventListener {
3 void onEvent();
4 }
5
6 // 定义一个管理事件监听器类
7 public class EventSource {
8 private List<EventListener> source = new ArrayList<>(10);
9
10 public void registerListener(EventListener listener) {
11 try {
12 Thread.sleep(500L);
13 } catch (InterruptedException e) {
14 e.printStackTrace();
15 }
16 listener.onEvent(); //假设listener注册500ms就被调用了
17 source.add(listener);
18 }