DMB3
DMB3

Reputation: 321

Scheduling recurring tasks in Java without them stopping on unchecked exceptions

I have a very simple Runnable that I want to schedule for execution every 30 seconds - bear in mind that this is just a simple example for this question's sake and not the actual point of using this in reality.

@Override
public void run() {
    System.out.println("Throwing an unchecked exception on purpose...");
    int abc = 123 - 123;
    int def = 123 / abc;
}

I was using Timer and TimerTask but ran into a problem: whenever the TimerTask raised an unchecked exception, any subsequent execution of that task would be cancelled; thus the task above would actually only run once because it would throw an unchecked division by 0 Exception.

As far as I know, ScheduledThreadPoolExecutor has the exact same "feature", at least according to the official Java API documentation "If any execution of the task encounters an exception, subsequent executions are suppressed".

Is there any standard way in Java to make either Timer or ScheduledThreadPoolExecutor to don't suppress subsequent executions if an unchecked exception is raised?

Many thanks.

Upvotes: 1

Views: 521

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502096

Is there any standard way in Java to make either Timer or ScheduledThreadPoolExecutor to don't suppress subsequent executions if an unchecked exception is raised?

Well there's one really simple way - create an ExceptionSuppressingRunnable which wraps another one:

public final class ExceptionSuppressingRunnable implements Runnable
{
    private final Runnable original;

    public ExceptionSuppressingRunnable(Runnable runnable)
    {
        // TODO: Null validation
    }

    public void run()
    {
        try
        {
            original.run();
        }
        catch (RuntimeException e)
        {
            // TODO: Logging
        }
    }
}

Note that this deliberately doesn't catch Error (or any other non-Exception subclass of Throwable). You could catch Exception instead of RuntimeException - it would only make a difference in weird cases where code threw a checked exception without declaring it (due to byte code rewriting, versioning differences or whatever). I think it's probably clearer to just catch RuntimeException.

Upvotes: 4

Related Questions