5

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

Biscuit128
  • 5,026
  • 21
  • 84
  • 142

3 Answers3

4

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

akostadinov
  • 16,273
  • 6
  • 71
  • 81
  • 1
    This makes sense because it's an auxiliary Thread, and it's not making the main job, so can be marked as a daemon Thread. – Jose Renato Apr 16 '13 at 13:27
1

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.

Freiheit
  • 7,925
  • 6
  • 57
  • 99
1

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.

Jatin
  • 29,900
  • 12
  • 95
  • 152