A call is made periodically through the ScheduledExecutorService

I have a Callable<String> . I want to run it periodically through ScheduledExecutorService.scheduleAtFixedRate() and get a list of all the rows that were returned by .call() calls on my called. Since scheduleAtFixedRate does not accept Callable ( Runnable s only), I need to deploy a custom Runnable that wraps my Callable , something like these lines:

 final Callable<String> myCallable = ....; final ConcurrentLinkedQueue<String> results = new ConcurrentLinkedQueue<String>(); Runnable r = new Runnable() { @Override public void run() { try { results.add(myCallable.call()); } catch (Exception e) { results.add(null); // Assuming I want to know that an invocation failed } } }; ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate(r, 0, 1, TimeUnit.SECONDS); 

Naturally, I would not want to roll back my own things (especially in multi-threaded code), so I think there is a JDK class that does this kind of aggregation?

+8
java java.util.concurrent
source share
1 answer

What you do above refers to your Callable implementation as a simple normal class. You are not sending the calling ThreadPool artist. Calling Callable.call () does not use ThreadPoolExecutor.

You need to submit your task (Runnable / Callable / ForkJoinTask, etc.) to ThreadPool in order to use the thread pool. You can use Futures to collect results after execution.

ForkJoinPool is one option you can try, it is part of JDK 7. See tasks and join them using ForkJoinTask Why not use futures? They are intended to understand the status of the task and its result.

You looked at this: Using Callable to return results from Runnables

0
source share

All Articles