java - ScheduledExecutorService not printing the exception stacktrace when the run method throws NPE -
in code given below, i.intvalue
throwing npe
. not printed. instead scheduledexecutorservice
terminates silently cancelling subsequent executions . why?
import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.*; class concurr { public static void main(string[] args) { scheduledexecutorservice sce = executors.newscheduledthreadpool(1); runnable task = new runnable() { public void run() { system.out.print("."); integer = null; i.intvalue(); } }; final scheduledfuture<?> future = sce.scheduleatfixedrate(task,0,2,timeunit.seconds); sce.schedule( new runnable() { public void run() { future.cancel(true); } },10,timeunit.seconds); } }
an executorservice
catches (and stores) exceptions thrown in runnable
, callable
instances manages.
the scheduledfuture
has get()
method throws executionexception
containing exception if 1 thrown during execution of runnable
. throws cancellationexception
if execution cancelled.
do
system.out.println(future.get()); // returns null otherwise
at end of main
. following output:
.exception in thread "main" java.util.concurrent.executionexception: java.lang.nullpointerexception @ java.util.concurrent.futuretask$sync.innerget(unknown source) @ java.util.concurrent.futuretask.get(unknown source) @ test.main.main(main.java:50) caused by: java.lang.nullpointerexception @ test.main$1.run(main.java:38) @ java.util.concurrent.executors$runnableadapter.call(unknown source) @ java.util.concurrent.futuretask$sync.innerrunandreset(unknown source) @ java.util.concurrent.futuretask.runandreset(unknown source) @ java.util.concurrent.scheduledthreadpoolexecutor$scheduledfuturetask.access$301(unknown source) @ java.util.concurrent.scheduledthreadpoolexecutor$scheduledfuturetask.run(unknown source) @ java.util.concurrent.threadpoolexecutor.runworker(unknown source) @ java.util.concurrent.threadpoolexecutor$worker.run(unknown source) @ java.lang.thread.run(unknown source)
you use , pass callable
instead of runnable
executorservice
if asynchronous task should return value. value future.get()
.
each call future.get()
returns result of 1 execution of runnable
. example, you've scheduled task run every 5 seconds. if after 16 seconds, call
future.get(); future.get(); future.get(); future.get();
the code block on 4th call because others have finished , have returned result (unless 1 of them failed).
Comments
Post a Comment