What is the volatile keyword in Java for? Explain with examples
Hello everyone! I'm a beginner Java developer and have been actively studying multithreading recently. I came across the `volatile` keyword, but I don't fully understand why it's needed and when to use it.
I wrote a small piece of code where one thread changes the `running` flag, and another thread checks it in a loop. Without `volatile`, the program sometimes works incorrectly — the second thread doesn't see the change and continues running.
Here's my code:
```java
public class TestVolatile {
private static boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (running) {
// do something
}
System.out.println("Worker stopped");
});
worker.star
No answers yet.
Log in to leave an answer