As i understand, if we declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main mem
Here is an example showing a variable that is accessed by two threads. The StarterThread thread sets the variable started when the thread starts. The WaiterThread waits for the variable started to be set.
public class Main
{
static /*volatile*/ boolean started = false;
private static class StarterThread extends Thread
{
public void run()
{
started = true;
}
}
private static class WaiterThread extends Thread
{
public void run()
{
while (!started)
{
}
}
}
public static void main(String[] args)
{
new StarterThread().start();
new WaiterThread().start();
}
}
If started is not volatile, then there is no synchronization point that guarantees that WaiterThread will ever get the updated value of the started variable. Consequently, the WaiterThread thread could potentially run "indefinitely".