I have a daemon thread which is started when a page is opened. The thread is then stopped when the page is closed. So in my class which holds the thread, I have it created like this:
class A {
private static volatile boolean isStopped=false;
//this method is called then the page is loaded
public void testListener() {
Thread listener = new Thread(new Runnable() {
public void run() {
while(!isStopped) {
//perform listener event
try {
//after every event sleep for a while
Thread.sleep(1000 *2)
} catch(InterruptedException e){}
}
}
});
}
listener.setName("Test-Server-Daemon");
listener.setDaemon(true);
listener.start();
// reset back to false so thread can be restarted when the page load event,
// call this method instance
if (isStopped) {
isStopped=false;
}
}
/**This is called when page is closed**/
public static void stopListener() {
isStopped=true;
}
}
Upon investigation, I have noticed that when the page is closed and not opened again within say 30 seconds interval, the thread is gracefully stopped.
But when the page is closed and re-opened within say 2 seconds interval the old thread does not get stopped and hence runs simultaneously with a new one.
And so as you can see from below image, I have the same thread started again when I close and quickly open the page.
Do anyone knows how to prevent this from occurring?
I have tried using thread interrupt where I reset the mutex but no joy.
EDITED:
isStopped is volatile.

To follow on from @Jordão’s answer, the
isStoppedvariable should be per thread. I would recommend using something like anAtomicBooleanand changing your thread code to be approximately:Then back in your page controller you can do: