Quiz 6

Questions regarding memory visibility in multithreaded scenarios

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?

Q
A)

loops forever and doesn’t print anything

B)

prints 5

C)

prints 2

D)

May loop forever or print 2 or print 5

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 ...