我想弄清楚下面的代码是否存在任何潜在的并发问题。具体而言,可见性问题与易变变量有关。 挥发性定义为:这个变量的值将不会被缓存线程本地:所有读取和写入将直接进入“主内存”并发性,对象可见性
public static void main(String [] args)
{
Test test = new Test();
// This will always single threaded
ExecutorService ex = Executors.newSingleThreadExecutor();
for (int i=0; i<10; ++i)
ex.execute(test);
}
private static class Test implements Runnable {
// non volatile variable in question
private int state = 0;
@Override
public void run() {
// will we always see updated state value? Will updating state value
// guarantee future run's see the value?
if (this.state != -1)
this.state++;
}
}
对于上述单线程执行:
是否可以做test.state非易失性?换句话说,将会每次连续执行Test.run()(这将会按顺序发生而不是同时执行,因为executor是单线程的),总会看到更新的test.state值?如果没有,不退出Test.run()确保所做的任何更改使得线程在本地被写回主内存?否则,当线程在本地进行更改时,如果线程退出时还没有写回主内存?
你从哪儿弄来该定义。听起来像一个1.5 JMM之前的定义(这是不可实现的)。 –
http://www.javamex.com/tutorials/synchronization_volatile.shtml – Integer
认识到线程完成Test.run()时很重要,线程不会终止,并且任何有关由线程在终止之前刷新到主内存不适用。调用Test.run()的'run()'方法线程只是一个循环,它会阻塞,直到它接收到一个要执行的新任务。当该任务从*它的'run()'方法返回时,该线程将阻塞直到下一个任务;它不会终止(从而刷新其状态)。 – erickson