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