Simplest and understandable example of volatile keyword in Java

后端 未结 12 851
梦谈多话
梦谈多话 2020-11-28 19:43

I\'m reading about volatile keyword in Java and completely understand the theory part of it.

But, what I\'m searching for is, a good case example, which sho

12条回答
  •  执念已碎
    2020-11-28 20:48

    What is volatile keyword ?

    volatile keyword prevents caching of variables.

    Consider the code ,first without volatile keyword

    class MyThread extends Thread {
        private boolean running = true;   //non-volatile keyword
    
        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,this program should print hello until RETURN key is pressed. But on some machines it may happen that variable running is cached and you cannot change its value from shutdown() method which results in infinite printing of hello text.

    Thus using volatile keyword ,it is guaranteed that your variable will not be cached ,ie will run fine on all machines.

    private volatile boolean running = true;  //volatile keyword
    

    Thus using volatile keyword is a good and safer programming practice.

提交回复
热议问题