I have a thread in my application which is permanently running sending heartbeat every 5 minutes to a monitoring application.
If my application fails in an exception block I need to exit the thread that is running it (the while loop is based on the thread not being interrupted).
Does this mean in every catch i will need a system exit or a call to interrupt that thread? This seems a very messy approach but I do not know how else too.
Thanks
you can designate this thread to be a daemon thread. It will terminate with application.
Consider using an object readable by both the main application and the thread. If the main application encounters an exception it should have a finally
block wich sets that object telling the heartbeat thread that the application has or is shutting down.
This might give you a mechanism for the heartbeat to send out one last "dead" message. This can tell the monitor that your application died and list the reason rather than simply not sending a heartbeat.
Ideally, you would want a way of transmitting a message from application to the thread, to terminate.
This depends on the expression your while loop is based upon. If currently your code is of type:
while(expression)
Where expression returns some boolean, it can always be replaced with:
while(Thread.currentThread.interrupted()){
if(!expression)
break;
//....
}
This would be the perfect solution. Or you can use some boolean to also notify. Or probably if your while
is based on queue, then add some POISON_PILL, which shall represent that it is time to come out of loop.
Daemon thread
is also a solution is mentioned above, but it depends if you want to store some data or close/manage some resources. It would be an issue then.
Ultimately for robustness, you need to come up with a suitable shutdown policy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With