Search⌘ K
AI Features

Quiz 6

Explore memory visibility challenges in Java multithreading, including how unsynchronized threads may see stale data. Learn how synchronization and the volatile keyword guarantee visibility and prevent reordering, ensuring threads read the latest values for shared variables. This lesson covers practical examples that clarify common concurrency pitfalls and solutions for consistent thread communication.

We'll cover the following...

Question # 1

Consider the below class:

public class MemoryVisibility {

    int myvalue = 2;
    boolean done = false;

    void thread1() {

        while (!done);
        System.out.println(myvalue);

    }

    void thread2() {

        myvalue = 5;
        done = true;
    }
}

We create an object of the above class and have two threads run each of the two methods like so:

        MemoryVisibility mv = new MemoryVisibility();

        Thread thread1 = new Thread(() -> {
            mv.thread1();
        });

        Thread thread2 = new Thread(() -> {
            mv.thread2();
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

What will be the output by thread1?

Technical Quiz
1.
A.

loops forever and doesn’t print anything

B.

prints 5

C.

prints 2

D.

May loop forever or print 2 or print 5


1 / 1

Show Explanation

This is a classic gotcha moment for a newbie to Java concurrency. Remember in the absence of synchronization, the compiler, processor or the runtime are free to take liberty in reordering operations. There's no guarantee that the values written to myvalue and done by thread2 are visible to thread1 in the same order or visible at all. The updated values may reside in the processor cache and not be immediately propagated to main memory from where thread1 reads. It's also possible that thread1 sees updated value for one of the variables and not for another. Synchronization is not only about mutual exclusion but also about memory visibility.

Question # 2

...