Skip to content

Month: May 2021

Exception handling in ScheduledExecutorService

Java’s ScheduledExecutorService allows you to schedule Runnable tasks without having to worry too much about creating Threads. At its simplest, you can schedule a task like this:

Runnable task = () -> System.out.println("Hello world!");
executor.schedule(task, 10, TimeUnit.SECONDS);
System.out.println("Done!");

The output is:

Done!
Hello world!

That is we schedule the task, then print “Done!”. 10 seconds later the scheduled task executes and prints “Hello world!”.

But what happens if the Runnable throws an Exception?