I have a background thread which will not start processing until it’s start variable becomes true:
class MyBackgroundThread implements Runnable {
// ...
public void run() {
while(true) {
if(!start) continue;
doSomethingWith(myValue);
}
}
}
The start variable is set to true from clicking a button on a JFrame which is of course running on the Event Dispatch Thread. There’s also a myValue field in the background thread class, which is set from clicking the button:
startBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
backgroundThreadInstance.setMyValue(100);
backgroundThreadInstance.setStart(true);
// ...
}
});
As you can see, it assigns something to myValue before setting start to true. Does this mean that setting myValue and start as volatile is not required? Since myValue is written to first, it will be leaked to the background thread before start is, thus the background thread will never get the chance to process an uninitialised myValue?
Short answer is yes. Though, in practice, eventually the change to true would likely be seen by your thread, in theory it might never happen.
However, agree with @NamshubWriter that there are better ways to do this than an busy/idle loop. I like his proposal to set the integer and then submit it to an ExecutorService. e.g.
One difference is that if they hit the button multiple times you would have several runnables started. Which may or may not be what you want.