有什么意义使用volatile long吗? [英] Is there any point in using a volatile long?
本文介绍了有什么意义使用volatile long吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有时会使用 volatile
实例变量,在这种情况下,我有两个线程从/写到它,并且不希望开销(或潜在的死锁风险)取出锁;例如定时器线程周期性地更新在某些类上作为getter暴露的int ID:
I occasionally use a volatile
instance variable in cases where I have two threads reading from / writing to it and don't want the overhead (or potential deadlock risk) of taking out a lock; for example a timer thread periodically updating an int ID that is exposed as a getter on some class:
public class MyClass {
private volatile int id;
public MyClass() {
ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);
execService.scheduleAtFixedRate(new Runnable() {
public void run() {
++id;
}
}, 0L, 30L, TimeUnit.SECONDS);
}
public int getId() {
return id;
}
}
注意事项:请勿回复说使用 volatile
over synchronized
是预优化的情况;我很清楚如何/何时使用同步
,但有些情况下优先使用 volatile
。例如,当定义一个用于单线程应用程序的Spring bean时,我倾向于使用 volatile
实例变量,因为不能保证Spring上下文将初始化每个bean