发布对象线程安全问题

发布对象,对象逸出并发问题详解

发布对象(NotThreadSafe)

使一个对象能够被当前范围之外的代码所使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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()));
}
}

对象逸出(NotThreadSafe)

一种错误的发布。当一个对象还没有构建完成时,就使它被其他线程所见。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@NotThreadSafe
@NotRecommend
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();
}
}