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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With