安全发布对象-发布与逸出
1.什么叫不安全发布,发布之后的对象会被其他对象不安全的改变值
@Slf4j
@NotThreadSafe
public class UnsafePublish {
private String[] states = {"a", "b", "c"};
public String[] getStates() {
return states;
}
public static void main(String[] args) {
UnsafePublish unsafePublish = new UnsafePublish();
log.info("{}", Arrays.toString(unsafePublish.getStates()));
unsafePublish.getStates()[0] = "d";
log.info("{}", Arrays.toString(unsafePublish.getStates()));
}
}
output
11:57:24.909 [main] INFO top.xiongmingcai.example.UnsafePublish - [a, b, c]
11:57:24.914 [main] INFO top.xiongmingcai.example.UnsafePublish - [d, b, c]
类初始化未结束,外部就可以使用他的this指针了。这里的逸代表的是逃逸的意思,提前逃出去了
@Slf4j
@NotRecommend
@NotThreadSafe
public class Escape {
private int thisCanBeEscape = 0;
public Escape() {
new innerClass();
}
private class innerClass {
public innerClass() {
//在对象未构建之前不可以将其发布
log.info("{}", Escape.this.thisCanBeEscape);
}
}
public static void main(String[] args) {
new Escape();
}
}
