【发布时间】:2022-01-31 19:14:47
【问题描述】:
该问题仅涉及当前提供的示例(不是一般性的):
在这里省略mutableVariable 的“volatile”关键字是否安全,或者在线程安全方面绝对有必要添加它?
mutableVariable 只能在 Main-Thread 中访问,但由于 lambda 表达式,我不知道它是否通过 Thread-2 “传递”,因此可以缓存在那里,或者 Thread-2 只看到缓存值?
感谢您的回答和最诚挚的问候。
package test.java;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.junit.Test;
public class A {
private final BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<Runnable>();
private int mutableVariable = 1; // is "volatile"-keyword absolutely necessary here, or can it be omitted?!
@Test
public void test() throws InterruptedException {
// executed in Thread-Main
final Thread thread = new Thread(() -> {
// executed in Thread-2
this.blockingQueue.add(() -> {
// executed in Thread-Main
this.mutableVariable++;
System.out.println(this.mutableVariable); // should always be 3
});
});
// executed in Thread-Main
this.mutableVariable = 2;
thread.start();
final Runnable r = this.blockingQueue.take();
r.run();
}
}
【问题讨论】:
-
Is it safe to omit the the "volatile"-keyword for mutableVariable here在这个非常具体的情况下,是的。 -
TLDR:新线程持有对 lambda 的引用这一事实无关紧要:唯一重要的是哪个线程执行 lambda 主体。只有主线程会这样做。
标签: java multithreading lambda thread-safety volatile