【发布时间】:2018-10-06 14:51:42
【问题描述】:
package test1;
import java.util.Random;
public class OneInstanceService {
// use volatile or final,them has same effect,
// but difference volatile or final in DCL demo?
public int i_am_has_state;
private static OneInstanceService test;
private OneInstanceService() {
i_am_has_state = new Random().nextInt(200) + 1;
}
public static OneInstanceService getTest1() {
if (test == null) {
synchronized (OneInstanceService.class) {
if (test == null) {
test = new OneInstanceService();
}
}
}
return test;
}
public static void reset() {
test = null;
}
}
//----------------------------------------
package test1;
import java.util.concurrent.CountDownLatch;
public class Test1 {
public static void main(String[] args) throws InterruptedException {
for (;;) {
CountDownLatch latch = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(100);
for (int i = 0; i < 100; i++) {
Thread t1 = new Thread() {
@Override
public void run() {
try {
latch.await();
OneInstanceService one = OneInstanceService.getTest1();
if (one.i_am_has_state == 0) {
System.out.println("one.i_am_has_state == 0 process exit");
System.exit(0);
}
end.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
}
latch.countDown();
end.await();
OneInstanceService.reset();
}
}
}
只使用:
public int i_am_has_state;
运行结果是:
System.out.println("one.i_am_has_state == 0 process exit");
System.exit(0);
但修改代码底部:
volatile public int i_am_has_state;
或
final public int i_am_has_state;
没有运行底部代码:
System.out.println("one.i_am_has_state == 0 process exit");
System.exit(0);
我的问题是: DCL 使用最终确定 DCL 使用 final volatile ok
所以 在 DCL final 和 volatile 的区别?
非常感谢!
【问题讨论】:
-
我认为你搞混了。 DCL 要求
test是可变的,除非OneInstanceService是线程安全的。 -
嗨 shmosel,但我也测试了最终的线程保存。final 和 volatile 它们没有重新排序效果?
-
@Gaohongyan 过马路不用看左右,也不会被车撞到。这并不意味着它是安全的。
-
你很困惑。这里的 DCL 与
i_am_has_state完全无关。它使用test变量。
标签: java multithreading thread-safety final volatile