Java Volatile Keyword Explained

In Java, the volatile keyword is used to decorate variables to ensure their visibility and ordering in a multi-threaded environment. When a variable is declared as volatile, each thread will read the latest value of that variable from the main memory instead of from the thread’s local cache, in order to prevent data inconsistency between threads.

The way to use the volatile keyword is as follows:

public class VolatileExample {
    private volatile boolean flag = false;

    public void setFlag() {
        flag = true;
    }

    public boolean getFlag() {
        return flag;
    }

    public static void main(String[] args) {
        VolatileExample example = new VolatileExample();

        new Thread(() -> {
            example.setFlag();
            System.out.println("Flag is set to true");
        }).start();

        while (!example.getFlag()) {
            // Do nothing until flag is set to true
        }

        System.out.println("Flag is now true");
    }
}

In the example above, the flag variable is declared as volatile to ensure visibility in a multi-threaded environment. In the main thread, the value of the flag is checked by calling the getFlag method. If it is false, the loop continues waiting for the flag to be set to true. In another thread, the flag is set to true by calling the setFlag method. This ensures that the flag value obtained in the main thread is the latest and that the operations between threads are orderly.

bannerAds