Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my boolean variable should be volatile while stopping thread loop? [duplicate]

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?

like image 506
Wojciech Kazior Avatar asked Sep 18 '16 13:09

Wojciech Kazior


People also ask

Why is it important to declare the boolean variable finished as volatile?

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.

Is volatile Boolean thread safe?

volatile boolean can be safely written to, just not negated; negation is a read-modify-write cycle. But just myVolatileBool = false; is threadsafe - because that's what volatile does, forces any writes to go to the same heap memory, and forces any reads to come from heap memory.

When should volatile be used?

Yes, volatile must be used whenever you want a mutable variable to be accessed by multiple threads. It is not very common usecase because typically you need to perform more than a single atomic operation (e.g. check the variable state before modifying it), in which case you would use a synchronized block instead.

Why do we need volatile variables in Java?

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.


1 Answers

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 enter image description here

like image 101
Md Ayub Ali Sarker Avatar answered Oct 07 '22 09:10

Md Ayub Ali Sarker