I have the following code
import java.util.concurrent.*;
public class dsd {
private static boolean stopRequested;
private static void requestStop() {
stopRequested = true;
}
private static synchronized boolean stopRequested() {
return stopRequested;
}
public static void main(String[] args)
throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested())
i++;
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
requestStop();
}
}
The question is why it works even if requestStop() is not synchronized? If I try to do the same thing to the stopRequested(), it doesn't work anymore. Why is there no problem with concurrency of the threads on that variable? I know that synchronization makes a variable appear in a consistent state by other threads. But here the variable is not synchronized and it seems that is has no effect.
synchronizedto the declaration ofstopRequested()?