Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit application correctly

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

like image 434
Biscuit128 Avatar asked Apr 16 '13 13:04

Biscuit128


3 Answers

you can designate this thread to be a daemon thread. It will terminate with application.

like image 95
akostadinov Avatar answered Sep 22 '22 11:09

akostadinov


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.

like image 21
Freiheit Avatar answered Sep 22 '22 11:09

Freiheit


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.

like image 24
Jatin Avatar answered Sep 23 '22 11:09

Jatin