Wojciech Kazior Wojciech Kazior - 1 year ago 56
Java Question

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

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;

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();
// do something

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

Answer Source

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