Search⌘ K

Volatile

Explore the role of the volatile keyword in Java multi-threading to ensure that updates to a variable are visible across threads. Learn why volatile can prevent unpredictable behavior without requiring synchronization when a variable is read by one thread and written by another.

We'll cover the following...
1.

Explain the concept of volatile

Show Answer
Did you find this helpful?
Technical Quiz
1.

Consider the class setup below:

class TaleOfTwoThreads {

    boolean flag = true;

    public void signalToStop() {
        flag = false;
    }


    public void run() {

        while (flag) {

            // ... Run like crazy
        }
    }
}

When will the “All Done” statement be printed for the following snippet

        TaleOfTwoThreads example = new TaleOfTwoThreads();

        // start runner thread
        Thread runner = new Thread(() -> example.run());
        runner.start();

        // wait for one second before signalling to stop
        Thread.sleep(1000);
        Thread stopper = new Thread(() -> example.signalToStop());
        stopper.start();

        // wait for two threads to complete processing
        stopper.join();
        runner.join();
        System.out.println("All Done");

A.

Printed roughly after one second

B.

Exception thrown because we aren’t synchronizing access to flag

C.

Never printed

D.

May be printed after atleast one second


1 / 1

The answer may seem ...