I have a program which creates 10 threads, and each thread has an infinitely running while loop. I need help to efficiently implement a Shutdown hook which can effectively STOP all the threads. Since I want to do a graceful shutdown each Thread should finish as soon as it finds the stop flag turned to TRUE.
public class SampleGSH implements Runnable{
private static boolean stop = false;
public static void main(String[] args) {
for(int i = 0; i < 10;i++) {
Thread t = new Thread(new SampleGSH(), "name"+i);
t.start();
}
}
@Override
public void run() {
Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {
public void run()
{
System.out.println("*******");
synchronized (this)
{
System.out.println("Turning switch off");
stop = true;
}
}
});
synchronized (this) {
while(!stop)
{
//Some logic which should not be killed abruptly once it starts running, a graceful shut down will not allow this code to start
}
}
}
}
Any help will be truly appreciated.
I need help to efficiently implement a Shutdown hook which can effectively STOP all the threads.
If you have any fields that are shared between multiple threads, they need to be synchronized. In this case your stop
should be volatile
. Without this, there is nothing that ensures that the threads will see the value of stop
change to true
. See this tutorial for information about atomic access.
See: Using boolean var for stopping threads
Couple other comments:
If you are starting a number of threads, you should consider using an ExecutorService
Your while
loop is inside of a synchronized
block. This does nothing and the stop
field will not get memory synchronized since it gets updated externally while inside of the block.
Another way to stop a thread would be to interrupt()
it. See this tutorial.
while (!thread.currentThread().isInterrupted()) {
...
}
...
t.interrupt();