volatile keyword in Java

For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.

```
import java.util.Scanner;

class MyThread extends Thread {
    private volatile boolean running = true;   // volatile keyword is needed here

    public void run() {
        while (running) {
            System.out.println("hello");
        }
    }

    public void shutdown() {
        running = false;
    }
}

public class Main {

    public static void main(String[] args) {
        MyThread obj = new MyThread();
        obj.start();

        Scanner input = new Scanner(System.in);
        input.nextLine(); 
        obj.shutdown();   
    }    
}
```
Ideally, if without volatile, this program should print hello until the Return key is pressed. But on some machines it may happen that the variable running is cached and you cannot change its value from the shutdown() method which results in infinite printing of the hello text.
Thus, by using the volatile keyword, it is guaranteed that your variable will not be cached and the code will run fine on all machines.