java - 如何围绕未正确发布的值演示竞争条件?

标签 java concurrency

我正在阅读“Java 并发实践”并查看第 51 页的示例代码。

根据这本书,这段代码如果没有正确发布,就有失败的风险。因为我喜欢编写示例代码并分解它们以证明它们是如何工作的。我尝试让它抛出 AssertionError 但失败了。 (引导我到我的 previous question )

任何人都可以发布示例代码以便抛出 AssertionError 吗?规则:不要修改 Holder 类。

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");
        }
    }
}

我已经修改了该类,使其更加脆弱,但我仍然无法抛出 AssertionError。

class Holder2 {
    private int n;
    private int n2;

    public Holder2(int n) throws InterruptedException{
        this.n = n;
        Thread.sleep(200);
        this.n2 = n;
    }

    public void assertSanity(){
        if (n != n2) {
            throw new AssertionError("This statement is false");
        }
    }
}

是否可以使上述任一类抛出 AssertionError?或者我们是否必须接受他们偶尔会这样做,而我们无法编写代码来证明这一点?

最佳答案

我会在多处理器计算机上运行它几个小时,看看会发生什么(如果您使用 Holder2,请删除 sleep )。这种竞争条件可能很少见,或者在您的特定机器上不存在 - 但至少尝试通过尝试数百万次来在一百万个案例中引发这些竞争条件。

class Checker {
  private Holder h;
  public Checker() {
   h = new Holder(42);
  }

  public void check() {
    h.assertSanity();
  }

  public void create(int n) {
   h = new Holder(n);
   }

}

public class MyThread extends thread{
  private bool check;
  private final Checker c;
  public MyThread(bool check,Checker c) {
    this.check = check;
    this.c = c;
  }
    public static void main(String[] args) {
      Checker c = new Checker();
      MyThread t1 = new MyThread(false,c);  
      MyThread t2 = new MyThread(true,c);
      t1.start();
      t2.start();
      t1.join();
      t2.join();
   }
   public void run() {
     int n = 0;
     while(true) {
       if(check) 
         c.check();
       else
         c.create(n++);
    }
   }
 }
}

关于java - 如何围绕未正确发布的值演示竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33500601/

相关文章:

java - 出现错误 java.lang.NoClassDefFoundError : com. google.android.gms.common.GooglePlayServicesUtil

java - 以下带有listiterator的代码无限运行

Scala Future 用于理解 : sequential vs parallel

java - WorkStealingPool 和 ThreadPoolExecutor 在与 CompletableFuture 一起使用时会产生不同的结果

java - 提交到 ScheduledExecutorService 的任务在 "waiting"运行时会做什么

java - 调整屏幕尺寸以进行 Selenium 测试

Java 堆空间不足,无法在 AWS S3 上上传文件

JavaFX Stage 显示空场景

c++ - 为什么在 C++ 中使用 std::atomic<double>、std::atomic<float> 时,compare_exchange_strong 会失败?

java - 使用可变键映射并发