Finding clarity in Java ScheduledExecutorService and FutureTask

I am just starting to learn Futures and ScheduledExecutorService in Java, and I wonder why my Callable does not work on the schedule you specify. In this code example, the caller starts once, but the application never terminates, and the task does not start again, as I expected (I am sure that the problem is related to my expectation).

Runnables work fine; Callables seem to block forever, but I'm not sure why .... What am I missing?

Thanks!

public class ExecutorExample { /** * @param args * @throws ExecutionException * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException, ExecutionException { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5); FutureTask<ArrayList<String>> ft1 = new FutureTask<ArrayList<String>>(new Callable<ArrayList<String>>(){ @Override public ArrayList<String> call() { ArrayList<String> stuff = new ArrayList<String>(); for(int i = 0;i<10;i++){ String thing ="Adding " + i + " to result"; stuff.add(thing); System.out.println(thing); } return stuff; }}); scheduler.scheduleAtFixedRate(ft1, 0, 1, TimeUnit.SECONDS); System.out.println(ft1.get()); System.out.println(ft1.isDone()); } } 
+6
java multithreading futuretask
source share
1 answer

The problem is that FutureTask used, and, as the documentation for its class says, "After the calculation is complete, the calculation cannot be restarted or canceled."

After the run FutureTask method FutureTask been called once, subsequent calls are immediately returned without delegation to the Callable task Callable .

As a recurring task, only Runnable can be used, and this does not allow the transfer of the result. Instead, give the Runnable a callback task that it can call at the end of its run method to report the results of each task execution back to listeners in other threads.

+8
source share

All Articles