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