Reputation: 197
So I have this very relevant thread I start when the program starts. The thread is listening to events coming from a bigger system as the main thread does other stuff. The thread should never stop working and if it does, it should be recreated and started.
I think I know multiple ways to achieve this, but I'd like to know your opinion on some things :
Upvotes: 1
Views: 1719
Reputation: 24857
This is a somewhat pointless and futile exercise. An app-lifetime thread should be debugged and made to not stop. The main thread of your app lasts for the process lifetime and any other threads should be designed, tested and debugged to the same standard.
What would happen if the thread that stopped had corrupted data in other threads when it crashed? If you just restarted it somehow, the data corruption may well make the situation worse.
Upvotes: 1
Reputation: 27115
The thread should never stop working and if it does,...
OK, so write it so that it will never stop working.
public void run() {
while (true) {
try {
Message message = receiveNextMessage();
handleMessage(message);
} catch (Exception ex) {
LOGGER.error(ex);
if (somethingTrulyHorribleHasHappened(ex)) {
Runtime.getRuntime().exit(1);
} else {
maybeResetSomethingThatNeedsToBeReset();
}
}
}
}
Upvotes: 1
Reputation:
If you are checking using normal Java provided methods to view the thread state correctly, you should not have any errors. In the case that a checked exception is thrown or the thread exits for some weird reason, a try-finally block should be sufficient to start a new thread (also ensure it is non-daemon). You could use a while loop with a periodic pause, preferably using a thread scheduling mechanism such as timed wait(...)
, or timed LockSupport#park(...)
. You can also sleep the thread as well.
Upvotes: 1
Reputation: 36
You can create the ExecutorService which is listening to the events via Executors.newSingleThreadExecutor()
.
In that case You don't have to take a look at the thread if it is healthy, the ExecutorService takes care of that. The SingleThreadExecutor is responsible that only one Task (Runnable or Callable) is running at one time.
Upvotes: 1