What is the volatile keyword useful for?

前端 未结 23 2600
闹比i
闹比i 2020-11-21 05:32

At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.

Given the detail in which that arti

23条回答
  •  [愿得一人]
    2020-11-21 06:09

    Below is a very simple code to demonstrate the requirement of volatile for variable which is used to control the Thread execution from other thread (this is one scenario where volatile is required).

    // Code to prove importance of 'volatile' when state of one thread is being mutated from another thread.
    // Try running this class with and without 'volatile' for 'state' property of Task class.
    public class VolatileTest {
        public static void main(String[] a) throws Exception {
            Task task = new Task();
            new Thread(task).start();
    
            Thread.sleep(500);
            long stoppedOn = System.nanoTime();
    
            task.stop(); // -----> do this to stop the thread
    
            System.out.println("Stopping on: " + stoppedOn);
        }
    }
    
    class Task implements Runnable {
        // Try running with and without 'volatile' here
        private volatile boolean state = true;
        private int i = 0;
    
        public void stop() {
            state = false;
        } 
    
        @Override
        public void run() {
            while(state) {
                i++;
            }
            System.out.println(i + "> Stopped on: " + System.nanoTime());
        }
    }
    
    

    When volatile is not used: you'll never see 'Stopped on: xxx' message even after 'Stopping on: xxx', and the program continues to run.

    Stopping on: 1895303906650500
    

    When volatile used: you'll see the 'Stopped on: xxx' immediately.

    Stopping on: 1895285647980000
    324565439> Stopped on: 1895285648087300
    

    Demo: https://repl.it/repls/SilverAgonizingObjectcode

提交回复
热议问题