LIP17 LIP17 -4 years ago 105
Java Question

Java8: How volatile field work with lambda

I am new to Java8 and multithreading work. I tried this piece of code below

public class Test {
public static boolean bchanged = true;

public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
while (true) {
if (bchanged != bchanged) {

new Thread((Runnable) () -> {
while (true) {
bchanged = !bchanged;

when I was running this code, there is no print of "here". However, when I change

public static volatile boolean bchanged = true;

then the "here" will be printed out.

My original deduction was that, the lambda will have a local copy of the boolean value, and it won't affect the other thread when it is not volatile, but when I tried print out the boolean value in both threads, it proved I was wrong. So I am very confused in this case, how
affect the way lambda work.

Answer Source

This isn't about lambdas, this is about accessing a shared variable in multiple threads. You need to use synchronized, locks, AtomicBoolean, volatile, or some other thread-safety alternative. With the code you wrote the compiler is likely to cache the value of bchanged. It doesn't know that there's another thread modifying it, so the first thread sees a stale cached value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download