Search⌘ K
AI Features

Volatile

Explore the role of the volatile keyword in Java multi-threading to ensure that updates to variables by one thread are visible to others. Understand why marking variables as volatile can prevent visibility issues and when synchronization is not required for thread safety. This lesson enhances your grasp of concurrency concepts essential for Java programming and interview preparation.

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 after approximately one second

B.

An exception is thrown because we are not synchronizing access to the flag variable

C.

May never be printed

D.

May be printed after at least one second, or not at all, depending on JVM optimizations and memory visibility.


1 / 1

The answer may seem ...