gpt4 book ai didi

java - 为什么我无法证明我的代码中需要 AtomicReference?

转载 作者:行者123 更新时间:2023-12-01 18:44:34 25 4
gpt4 key购买 nike

我有以下代码。显然,Reference 类不是线程安全的,因为它不保护其“引用”属性。我如何证明我需要通过例如原子引用来保护它?

当我运行以下 JUnit 测试时,它在 Windows:Intel(R) Core(TM) i5-2400 CPU @ 3.10GHz 和 Linux:Intel(R) Xeon(R) CPU X5670 @ 2.93GHz(使用 JRE 1.7)上成功.0_15.

import java.util.concurrent.CountDownLatch;
import org.junit.Test;
import static org.junit.Assert.assertTrue;

public class AssignReferenceTest {
private static class Reference {
private Object reference = null;

private void setReference(Object reference) {
this.reference = reference;
}

boolean hasReference() {
return reference != null;
}
}

@Test
public void runManyTimes() throws Exception {
for (int i = 0; i < 100000; i++) {
testReferenceVisibilityProblem();
}
}

public void testReferenceVisibilityProblem() throws Exception {
final Reference reference = new Reference();
final CountDownLatch latch = new CountDownLatch(1);

Thread writeThread = new Thread(new Runnable() {
public void run() {
reference.setReference(new Object());
latch.countDown();
}
});
Thread readThread = new Thread(new Runnable() {
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertTrue("Should have the reference", reference.hasReference());
}
});

writeThread.start();
readThread.start();
writeThread.join();
readThread.join();
}
}

最佳答案

您的代码是线程安全的,因为 CountDownLatch 保证在 await() 返回之前完成的每个更改都发生在之后完成的所有操作之前。

参见http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html :

Actions prior to "releasing" synchronizer methods such as Lock.unlock, Semaphore.release, and CountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.

关于java - 为什么我无法证明我的代码中需要 AtomicReference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18359466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com