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 { 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()); } }
java multithreading futuretask
marc
source share