例如 -
public class Request {
public String id; //is it visible to other threads after construction?
public Request(String id){
this.id= id;
}
}
答案 0 :(得分:3)
因为它是你的类不是线程安全的,即使在构造函数完成之后,线程也可以观察到id
的空值。
为了确保构造后所有线程都可以看到id
,您有几种可能性:
final
volatile
Request
对象。安全出版习语包括:
另请参阅this other post,其中解释了标记字段final以确保不可变对象的线程安全的重要性。