In Java, the `volatile` keyword 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 changes made by one thread to that variable are visible to other threads. This is particularly important in multi-threaded programming to avoid memory consistency errors.
Here is a simple code example demonstrating the use of the `volatile` keyword:
public class VolatileExample {
// Declare a volatile variable
private static volatile boolean running = true;
public static void main(String[] args) {
// Start a new thread
new Thread(() -> {
while (running) {
// Thread will continue running
}
System.out.println("Thread stopped.");
}).start();
// Main thread sleeps for a while
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the volatile variable
running = false; // This change will be visible to the other thread
}
}
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?