The Java volatile Keyword: Thread Safety and Performance Insights

·

The `volatile` keyword in Java ensures visibility of changes to a variable across threads. It prevents threads from caching the value, ensuring they always read from main memory. While `volatile` guarantees visibility, it doesn’t provide atomicity, so it is often used with simple read/write operations in multi-threaded environments.

Here’s an example:

public class VolatileExample {
    private static volatile boolean flag = true;

    public static void main(String[] args) {
        new Thread(() -> {
            while (flag) {
                // Loop until flag is changed
            }
            System.out.println("Flag changed");
        }).start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        flag = false;
    }
}
            

In this code, the `volatile` keyword ensures that changes to `flag` are immediately visible to other threads. Use it wisely, as it impacts performance when used with complex operations.

Comments

Leave a Reply

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