Java Timer class: timer tasks stop if an exception is thrown in one of the tasks

new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("run"); throw new SomeRandomException(); } }, 1000, 1000); 

Exit: start (exception thrown)

Here's the problem: I need a timer task to check for specific conditions in the database (or something else). It worked fine, but sometimes the database (or something else) returns some errors, an exception is thrown and a timer fails, and then another timer task fails. Is there any implementation of Timer that continues to work after an exception is thrown into run() .

I can

 new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { System.out.println("run"); throw new SomeRandomException(); } catch (Exception e) { System.out.println("dummy catch"); } } }, 1000, 1000); 

but it seems lame.

Another alternative is to write my own implementation of the Timer class, swallowing the exceptions of the run method (which seems also wrong).

+8
java timer
source share
2 answers

Use ScheduledExecutorService . It plays the same role as Timer, but fixes its shortcomings (for example, the one you are facing).

+7
source share

Using ExecutorService; , you can handle both compilation time and throw exceptions.

Handling Java ExecutorService Task Exceptions
How is exception handled in Callable

 ThreadPoolExecutor.java final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // allow interrupts boolean completedAbruptly = true; try { while (task != null || (task = getTask()) != null) { w.lock(); // If pool is stopping, ensure thread is interrupted; // if not, ensure thread is not interrupted. This // requires a recheck in second case to deal with // shutdownNow race while clearing interrupt if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()) wt.interrupt(); try { beforeExecute(wt, task); Throwable thrown = null; try { task.run(); } catch (RuntimeException x) { thrown = x; throw x; } catch (Error x) { thrown = x; throw x; } catch (Throwable x) { thrown = x; throw new Error(x); } finally { afterExecute(task, thrown); } } finally { task = null; w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); } } 
0
source share

All Articles