1

I encountered a problem about java multithreading in my graduate project. There are two threads. Thread A will execute an endless loop. In the loop, thread A will do something if the variable simulationSwitch is true. The boolean variable, simualtionSwitch is set to false initially so thread A will be busy waiting until simualtionSwitch is set to true.

Thread B handles http requests and sets simulationSwitch to true when receiving an http request.

Here comes the problem puzzling me. Thread A won't detect the change of simulationSwitch and do its job. However, if thread A calls Thread.sleep() in its loop, it can do its job properly if simulationSwitch is set to true by thread B. I'm really confused and want to figure out the reason.

public static boolean simulationSwitch = false;

// Thread A
public void startSimulation() throws Exception {
    while(true) {
        Thread.sleep(1000); // without calling Thread.sleep(), thread A won't do anything even if simualtionSwitch is set to true
        while (simulationSwitch) {
            // do something 
        }
    }
}

// this function will be called when receiving a specific http request
public void switchOn(){
    simulationSwitch = true;
}
NiHaoyin
  • 11
  • 1

1 Answers1

0

To ensure changes across threads are visible, simulationSwitch should be declared as volatile.

Without volatile, then the changes can still be visible in some circumstances but you can't rely on it.

fgb
  • 18,439
  • 2
  • 38
  • 52