Java: Volatile

|

The volatile keyword is used with variables that can be modified by multiple threads. Declaring a variable as volatile ensures that any change to it is immediately visible to all threads, preventing cached versions of the variable in different threads.

public class VolatileExample extends Thread {
    private volatile boolean running = true;

    public void run() {
        while (running) {
            System.out.println("Thread is running...");
        }
        System.out.println("Thread stopped.");
    }

    public void stopRunning() {
        running = false; // Volatile ensures this change is visible across threads
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileExample thread = new VolatileExample();
        thread.start();

        Thread.sleep(1000); // Let the thread run for a bit
        thread.stopRunning(); // Stop the thread by changing the volatile variable
    }
}

In this example, the running variable is declared as volatile, which means that any change to running is visible to all threads immediately. When stopRunning() is called, it sets running to false, and the run() method in the thread will stop.

Leave a Reply

Your email address will not be published. Required fields are marked *