I have a Runnable implementing class which will be run from a Executors.newFixedThreadPool
Inside the Runnable, I have an infinite-loop running which listens on an UDP Port for incoming data.
I want to gracefully end the Runnable in order to close said UDP Ports.
How can I achieve this?
When extending Thread directly, I have access to interrupt() and isInterupted() etc. on which I can base my infinite loop.
In the Runnable implementing class however, I want to to do something like
@Override
public void run() {
while (active) {
}
}
and have
private boolean active = true;
How can I set active = false when the ThreadPool is terminated?
You can access the interrupt flag of the current thread using the static method
Thread.interrupted(), e.g. instead of youractiveflag use:And when you want to shutdown your
ExecutorService, callshutdownNow()on it. This willinterrupt()any running worker threads and have yourRunnablebreak out of its loop.