Update on getting the exit status of a thread

This always winds up happening to me- I think I’ve found some clever way of doing things, and then about twenty minutes after I write about it, I discover a much better, much simpler alternative.

In the case of the previous post, I wanted to get the exit status of a thread- i.e. did it exit normally, or did it fail with an error? I wanted to know specifically so that I could restart it. Annoyingly, and conveniently, there is a much easier way of doing that using the SingleThreadScheduledExecutor(ThreadFactory) method in the ScheduledExecutorService class. You provide it with a Thread Factory that’s configured to create your process you don’t want to die, and this function will execute the process as scheduled, spawning a new thread from the ThreadFactory if the command exits with an exception.

scheduler = Executors.newSingleThreadScheduledExecutor(myThreadFactory);

ScheduledFuture<?> schedule = scheduler.scheduleAtFixedRate(new Runnable(), 0, 2, TimeUnit.WEEKS);

Bam. Two lines of code. As long as you don’t cancel it, your process will be running every two weeks. We can even query the exit status like the last post if we really want to know the post-mortem on our schedule object, but there’s not a lot of point to that.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s