[concurrency-interest] How to use Callable instead of Runnable with ScheduledThreadPoolExecutor?

Tim Peierls tim at peierls.net
Mon Oct 2 12:17:48 EDT 2006

It's hard to see how to make this work. Would you expect to receive the list
of Futures upon submission of the periodic task? In what order would you
wait for the results?

Instead, why not use a callback style?

interface PeriodicTaskListener<T> {
    void resultReturned(T result);
    void exceptionThrown(Exception exception);

class PeriodicTask<T> implements Runnable {
    private final Callable<T> callable;
    private final PeriodicTaskListener<T> listener;

    PeriodicTask(Callable<T> callable,
                 PeriodicTaskListener<T> listener) {
        this.callable = callable;
        this.listener = listener;

    public void run() {
        try {
        } catch (Exception e) {

Then you can use it like this:

scheduledThreadPool.scheduleAtFixedRate(new PeriodicTask<Long>(
    new Callable<Long>() {
        public Long call() throws Exception {
            ... compute some value ...
    new PeriodicTaskListener<Long>() {
        public void resultReturned(Long result) {
            ... do something with result ...
        public void exceptionThrown(Exception ex) {
            ... do something about ex ...
    5L, 5L, TimeUnit.SECONDS // every five seconds


On 10/2/06, Robert Bowen <syg6 at yahoo.com> wrote:
> Hello concurrent people,
> I have been futzing around with the Java 1.5 concurrent classes for a
> while now and more or less have the hang of things. But there is one thing I
> can't figure out. I'd like to schedule a task to execute every x seconds,
> have it return me a list of Futures for those tasks and, based on the result
> in each Future, do something.
> I'd like to use either scheduleAtFixedRate() or scheduleWithFixedDelay()but both of these take Runnable as their first parameter, and I'd like to
> use a Callable (to get a Result). I see that schedule() and submit() both
> take Callable as a parameter but that's for a one-shot execution, I need
> something periodic.
> Any way to do this?
> Many thanks guys,
> Bob
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20061002/43bf6714/attachment.html 

More information about the Concurrency-interest mailing list