java - How do I restart a scheduled thread if an exception occurs? -
i running thread scheduled run every 10 milliseconds scheduledexecutorservice. thread fails because of random uncaught exception, , wanted know how restart thread when happens. tried make thread global, , check if thread alive using scheduled thread, returns false when it running. tried check state of global thread, returned "new". appreciated! here code initializes everything:
scheduledexecutorservice scheduler = executors.newscheduledthreadpool(4); thread update = new thread(new updatethread()); scheduler.scheduleatfixedrate(update, 0, 10, timeunit.milliseconds);
whatever runnable you're passing executorservice should have body in try{} catch (runtimeexception) {/*log it*/}
block. javadoc scheduledexecutorservice.scheduleatfixedrate
explicitly says if scheduled runnable throws exception, future executions suppressed.
if reason don't want wrap body in try/catch - can use scheduledfuture
returned scheduleatfixedrate
; based on quick testing, calling get
on scheduledfuture block until execution of task fails uncaught exception.
as aside - shouldn't pass thread
executorservice
; service takes runnable
, , creates own thread
s internally.
Comments
Post a Comment