qwee
qwee

Reputation: 29

How to prove the volatile visibility guarantee?

I am reading an article about the Java Volatile keyword, got some questions. click here

public class SharedObject {

    public int counter = 0;

}

Imagine too, that only Thread 1 increments the counter variable, but both Thread 1 and Thread 2 may read the counter variable from time to time.

If the counter variable is not declared volatile there is no guarantee about when the value of the counter variable is written from the CPU registers back to main memory. This means, that the counter variable value in the CPU register may not be the same as in main memory.

How to verify that visibility cannot be guaranteed without volatile?

I have tried creating two threads A and B, where A executes counter=1 and asserts counter==1 in thread B. Counter is not decorated with volatile. However, asserts in thread B always succeed If the assert of thread B fails, it means that counter==0 is a visibility issue, but this has not happened If this is not easy to prove, do I need to use volatile to ensure visibility when writing a program where one thread writes to another thread for reading?

Upvotes: -1

Views: 80

Answers (1)

Andrey Smelik
Andrey Smelik

Reputation: 1266

To make sure volatile works, you can disable JIT compilation with the -Xint parameter and use this code:

public class VolatilityDemo {

    private static volatile boolean value = true;

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            while (value);
        }).start();
        Thread.sleep(1000);
        value = false;
    }
}

If you remove volatile, the thread will never terminate and the application will hang.

Upvotes: -1

Related Questions