2

I have next code:

boolean signal;

@Test
public void test() throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!signal){
                // empty loop body
            }
        }
    });
    thread.start();
    Thread.sleep(1000);
    signal = true;
    thread.join();
}

It runs infinity loop due to creation of local copy of signal variable in thread. I know that I can fix it by making my signal variable volatile. But also loop can successfully exit if add synchronized block inside my loop (even empty):

boolean signal;

@Test
public void test() throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!signal){
                synchronized (this) {

                }
            }
        }
    });
    thread.start();
    Thread.sleep(1000);
    signal = true;
    thread.join();
}

How synchronized updates my signal value inside thread?

3

1 Answer 1

1

Synchronized does not updates the signal value itself, it basically just places a couple of flags to avoid two threads use the same object at the same time; something like: MonitorEnter and MonitorExit.

The first one locks the object, and the second one releases.

Take a look at the following article: how-the-java-virtual-machine-performs-thread-synchronization.

Please notice the article is very old; but as far as I understand the logic behind remains.

Sign up to request clarification or add additional context in comments.

2 Comments

I know that, but why adding of synchronized block to loop updates signal variable in my second example?
Because the one without synchronized is a selfish thread; it means; it will stop until finishes its work; any thread can become a selfish thread if inside the loop it does not have a yield/sleep/Blocking Operation such I/O Now, when you placed the synchronized you make your selfish thread to be not selfish, since there is a blocking operation on the object "signal" The behavior itself depends a lot on the Infrastructure where you run it; but basically you have two threads there 1) main 2) thread and since the second is selfish it won't let main to continue...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.