User124235 User124235 - 1 month ago 6x
Java Question

Java Thread Synchronized methods

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())

The question is why it works even if
is not synchronized? If I try to do the same thing to the
, 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.


synchronized is reentrant, the same thread that acquired the lock of synchronized block is guaranteed that it'll keep it on the next try to acquired if it still own the lock, but this doesn't have to do with the fact that the change over stopRequested is made outside a synchronized block and still the code works, your code still may have a race condition under it actual circumstances.

Let say that at execution N the thread must terminate due on condition meet by stopRequested() and at the same time the requestStop() is called, it's not guaranteed that the thread terminate at N+1 because the variable stopRequested is not protected by exclusive lock in both accessor methods, nor the variable has volatile modifier. That means that the sense of correctness you have about the code, is partially wrong, because of race conditions.