Java – Best Practice for Exception Handling in Threads

exceptionsjavamultithreadingpatterns-and-practices

long-time reader, first-time asker here. I have a service which writes data to a database in batches. It contains a buffer which is being watched by a separate thread. Whenever the buffer reaches a certain size or a certain period of time has elapsed since the last write, the thread writes the data to the DB.

In Java, whenever there is an exception in the monitor thread, it just silently dies and never does anything again.

Is there an established best practice of handling exceptions in such threads? The thread must be running at all times and should print out an exception to the log if one occurs.

There are some potential solutions to this that come to mind:

  1. Wrap the entire methods in try/catch blocks, catch all exceptions and have a Logger print the messages. (Way too ugly for my taste)
  2. Register an uncaught exception handler and deal with the exceptions there. (maybe?)
  3. Do not use a Thread, but a Callable or a Runnable instead. (Not sure if this is suitable for always-running threads)
  4. Anything else?

Best Answer

Firstly, I didn't understand what you need the monitor thread for and what is it's purpose. The only reason I could think of is if the monitor thread is a continually running thread that just watches the buffer and periodically calls the database write. If that is the purpose, I would rather do it with schedulers, e.g. schedule a write every n seconds and write the whole buffer to the database. Then you just need to approximate how much seconds you need the scheduler rate to be in order for the buffer not to overflow.

As for the exception handling in threads, I would first retry the write. Ultimately, if everything fails, first thing you should do is salvage the data so it doesn't get lost.

The way exceptions are meant to be handled is to identify the exceptions that can occur and then only handle those specific exceptions. You should never do things like catch (Exception e). Since the DB writer service is a general service, I would have it propagate the exception to the caller and then have the caller handle the exception, since the service cannot know what behavior the caller wants.

As for how you should handle those specific exceptions is up to you and hardly anyone can help you with that. If you cannot handle the exceptions in finally block and they need developer's attention, I would log them or notify the developer through alternate communication channel, e.g. email, Slack.