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.
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();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?