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