1

This is How Synchronization Works
Let’s say we want to stop a thread , lets look at the below example. If you run below program you would see that the main thread does not see the value of the stopRequested and never stops.
If you run the below program , the backGround thread loops forever.
import java.util.concurrent.TimeUnit;
public class StopThread {
private static boolean stopRequested;
public static void main(String[] args) throws InterruptedException{
Thread backGroundThread= new Thread(()->{
int i=0;
while(!stopRequested)
i++;
});
backGroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested=true;
}
}
What is the Problem Here?
The Problem is in the absence of synchronization , there is no guarantee whether or when the backGround thread will see the modifications made to stopRequested by the main thread.
In the absence of synchronization the virtual machine will interpret the above code as:
while (!stopRequested)
i++;
to
if(!stopRequested)
while(true)
i++The above optimization is called hoisting and that is what open JDK VM does.
How To Solve for The liveness failure.
import java.util.concurrent.TimeUnit;
public class StopThreadSynchronized {
private static boolean stopRequested;
private static synchronized void requestStop() {
stopRequested = true;
}
private static synchronized boolean stopRequested() {
return stopRequested;
}
public static void main(String[] args) throws InterruptedException{
Thread backGroundThread= new Thread(()->{
int i=0;
while(!stopRequested())
i++;
});
backGroundThread.start();
TimeUnit.SECONDS.sleep(1);
requestStop();
}
}
It is important to note here that both the read and write must be synchronized .
The actions of the synchronized methods in StopThread would be atomic , the synchronization is required for the inter thread communication not for the mutual exclusion.

Please support me here if you want me to create such content, Stay tuned and thanks for reading.
