How does volatile behave in multithreaded code?

The `volatile` keyword in Java is used to indicate that a variable's value will be modified by different threads. When a variable is declared as `volatile`, it ensures that any read or write operation on that variable is directly from the main memory rather than from the thread's local cache. This means that changes made by one thread are immediately visible to other threads, which helps to avoid visibility issues in multithreaded programming.

Using `volatile` helps to ensure the correctness of the data in multithreaded environments where multiple threads may be reading and writing shared data concurrently.

However, `volatile` does not provide atomicity. For operations that require multiple steps to complete, additional synchronization mechanisms may still be needed.

Example of Volatile Usage in Java

class SharedResource { private volatile boolean flag = false; public void setFlagTrue() { flag = true; // This change is visible to other threads immediately } public boolean checkFlag() { return flag; // Reads the latest value from main memory } } public class Main { public static void main(String[] args) { SharedResource resource = new SharedResource(); Thread writer = new Thread(() -> { try { Thread.sleep(1000); // Simulate some work } catch (InterruptedException e) { e.printStackTrace(); } resource.setFlagTrue(); System.out.println("Flag set to true."); }); Thread reader = new Thread(() -> { while (!resource.checkFlag()) { // Busy wait } System.out.println("Flag is now true! Reader thread exiting."); }); writer.start(); reader.start(); } }

volatile multithreading Java concurrency shared variables thread safety