Why my boolean variable should be volatile while s

2020-02-01 04:52发布

问题:

Let's say I have a thread including while loop and I want to stop it "from outside".

public class MyThread extends Thread {

    private boolean running = true;

    @Override
    public void run() {
        while (running) {
            // do something
        }
    }

    public void setRunning(boolean running) {
        this.running = running;
   }
}

And here is the Main class:

public class Main {
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();
        // do something
        mt.setRunning(false);
    }
}

It seems to be stopping properly, but I have read that the boolean should be also volatile. Why? Will it quicken the stopping?

回答1:

When Concurrent thread will cache running variable that means it will cache in thread working memory.

The volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation you have to declare as volatile variable.

you can have good idea in you look into the below picture



回答2:

with Volatile state will be updated straight away in main memory. So as soon as running is updated , concurrent thread will see the updated state instantaneously.

Update :- It's working properly in your case probably because you don't have good number of multiple threads or if you have then by that time state has been updated in main memory by then. Best way to observe this kind of behavior to set up load tests (using tools like Jmeter). This indicates that why having good hold on theoretical/basic concepts matters otherwise you get these kind of issues on production environment which breaks your head as some projects don't have budget/timelines to do load testing