Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this simple threaded program get stuck?

Take a look at this simple Java program:

import java.lang.*;

class A {
    static boolean done;
    public static void main(String args[]) {
        done = false;
        new Thread() {
            public void run() {
            try {
                Thread.sleep(1000); // dummy work load
            } catch (Exception e) {
                done = true;
            }
            done = true;
            }
        }.start();
        while (!done);
        System.out.println("bye");
    }
}

On one machine, it prints "bye" and exits right away, while on another machine, it doesn't print anything and sits there forever. Why?

like image 810
Dog Avatar asked Aug 03 '26 23:08

Dog


1 Answers

This is because your boolean is not volatile, therefore Threads are allowed to cache copies of it and never update them. I would recommend an AtomicBoolean - that will prevent any issues you may have.

public static void main(String args[]) {
    final AtomicBoolean done = new AtomicBoolean(false);
    new Thread() {
        public void run() {
            done.set(true);
        }
    }.start();
    while (!done.get());
    System.out.println("bye");
}
like image 111
Boris the Spider Avatar answered Aug 05 '26 12:08

Boris the Spider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!