Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JCIP-发布线程的不安全发布和之前发生的事件_Java_Multithreading - Fatal编程技术网

Java JCIP-发布线程的不安全发布和之前发生的事件

Java JCIP-发布线程的不安全发布和之前发生的事件,java,multithreading,Java,Multithreading,清单3.15。如果未正确发布,则可能导致课程失败。 public class Holder { private int n; public Holder(int n) { this.n = n; } public void assertSanity() { if (n != n) throw new AssertionError("This statement is false."); } } // Unsafe publication public H

清单3.15。如果未正确发布,则可能导致课程失败。

public class Holder {
 private int n;
 public Holder(int n) { this.n = n; }    

 public void assertSanity() {
     if (n != n)
     throw new AssertionError("This statement is false.");
 }
} 
// Unsafe publication
public Holder holder;
public void initialize() {
 holder = new Holder(42);
} 
如果清单3.15中的持有者是使用清单3.14中的不安全发布习惯用法发布的,并且线程other 比起发布线程调用assertSanity,它还可能抛出AssertOnError! [15]

清单3.14。在没有充分同步的情况下发布对象。不要这样做。

public class Holder {
 private int n;
 public Holder(int n) { this.n = n; }    

 public void assertSanity() {
     if (n != n)
     throw new AssertionError("This statement is false.");
 }
} 
// Unsafe publication
public Holder holder;
public void initialize() {
 holder = new Holder(42);
} 
a) 第一个查询与发布线程本身相关,而与其他线程无关。如果发布线程执行以下操作-

1. Holder holder = new Holder (5); 
2. holder.getN() // is it guaranteed that this will print 5
根据程序顺序规则。线程中的每个操作都发生在 该线程中在程序顺序中稍后出现的每个操作

由于上述规则,
1 hb 2
,2将能够看到obj正确分配给持有者

但是,是否可以保证2也能够看到holder对象的安全构造,而不必在n声明前加上final修饰符


公共持有者(int n){this.n=n;}hb
1

什么是
hb
意思?如果我理解正确,问题是“有没有办法从观察者线程中提出断言错误?”答案是肯定的,作者在脚注#16中描述了这种方式。主要与字段
n
的可能“过时”值有关。3.5.2中描述了避免问题的方法。此外,这里还讨论了这个问题: