Cortwave
Cortwave

Reputation: 4907

How Java synchronize updates thread value?

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?

Upvotes: 2

Views: 69

Answers (1)

Marco Vargas
Marco Vargas

Reputation: 1327

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.

Upvotes: 1

Related Questions