Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7086047
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T07:30:03+00:00 2026-05-28T07:30:03+00:00

The ultimate goal is to add extra behavior to ListenableFuture s based on the

  • 0

The ultimate goal is to add extra behavior to ListenableFutures based on the type of the Callable/Runnable argument. I want to add extra behavior to each of the Future methods. (Example use cases can be found in AbstractExecutorService’s javadoc and section 7.1.7 of Goetz’s Java Concurrency in Practice)

I have an existing ExecutorService which overrides newTaskFor. It tests the argument’s type and creates a subclass of FutureTask. This naturally supports submit as well as invokeAny and invokeAll.

How do I get the same effect for the ListenableFutures returned by a ListeningExecutorService?

Put another way, where can I put this code

if (callable instanceof SomeClass) {
   return new FutureTask<T>(callable) {
        public boolean cancel(boolean mayInterruptIfRunning) {
            System.out.println("Canceling Task");
            return super.cancel(mayInterruptIfRunning);
        }
    };
} else {
    return new FutureTask<T>(callable);
}

such that my client can execute the println statement with

ListeningExecutorService executor = ...;
Collection<Callable> callables = ImmutableSet.of(new SomeClass());
List<Future<?>> futures = executor.invokeAll(callables);
for (Future<?> future : futures) {
    future.cancel(true);
}

Failed Solutions

Here’s a list of things I’ve already tried and why they don’t work.

Solution A

Pass MyExecutorService to MoreExecutors.listeningDecorator.

Problem 1: Unfortunately the resulting ListeningExecutorService (an AbstractListeningExecutorService) doesn’t delegate to the ExecutorService methods, it delegates to the execute(Runnable) method on Executor. As a result, the newTaskFor method on MyExecutorService is never called.

Problem 2: AbstractListeningExecutorService creates the Runnable (a ListenableFutureTask) via static factory method which I can’t extend.

Solution B

Inside newTaskFor, create MyRunnableFuture normally and then wrap it with a ListenableFutureTask.

Problem 1: ListenableFutureTask‘s factory methods don’t accept RunnableFutures, they accept Runnable and Callable. If I pass MyRunnableFuture as a Runnable, the resulting ListenableFutureTask just calls run() and not any of the Future methods (where my behavior is).

Problem 2: Even if it did call my Future methods, MyRunnableFuture is not a Callable, so I have to supply a return value when I create the ListenableFutureTask… which I don’t have… hence the Callable.

Solution C

Let MyRunnableFuture extend ListenableFutureTask instead of FutureTask

Problem: ListenableFutureTask is now final (as of r10 / r11).

Solution D

Let MyRunnableFuture extend ForwardingListenableFuture and implement RunnableFuture. Then wrap the SomeClass argument in a ListenableFutureTask and return that from delegate()

Problem: It hangs. I don’t understand the problem well enough to explain it, but this configuration causes a deadlock in FutureTask.Sync .

Source Code: As requested, here’s the source for Solution D which hangs:

import java.util.*;
import java.util.concurrent.*;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.*;

/** See http://stackoverflow.com/q/8931215/290943 */
public final class MyListeningExecutorServiceD extends ThreadPoolExecutor implements ListeningExecutorService {

    // ===== Test Harness =====

    private static interface SomeInterface {
        public String getName();
    }
    
    private static class SomeClass implements SomeInterface, Callable<Void>, Runnable {
        private final String name;

        private SomeClass(String name) {
            this.name = name;
        }

        public Void call() throws Exception {
            System.out.println("SomeClass.call");
            return null;
        }

        public void run() {
            System.out.println("SomeClass.run");
        }

        public String getName() {
            return name;
        }
    }

    private static class MyListener implements FutureCallback<Void> {
        public void onSuccess(Void result) {
            System.out.println("MyListener.onSuccess");
        }

        public void onFailure(Throwable t) {
            System.out.println("MyListener.onFailure");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Main.start");
        
        SomeClass someClass = new SomeClass("Main.someClass");
        
        ListeningExecutorService executor = new MyListeningExecutorServiceD();
        Collection<Callable<Void>> callables = ImmutableSet.<Callable<Void>>of(someClass);
        List<Future<Void>> futures = executor.invokeAll(callables);
        
        for (Future<Void> future : futures) {
            Futures.addCallback((ListenableFuture<Void>) future, new MyListener());
            future.cancel(true);
        }
        
        System.out.println("Main.done");
    }

    // ===== Implementation =====

    private static class MyRunnableFutureD<T> extends ForwardingListenableFuture<T> implements RunnableFuture<T> {

        private final ListenableFuture<T> delegate;
        private final SomeInterface someClass;

        private MyRunnableFutureD(SomeInterface someClass, Runnable runnable, T value) {
            assert someClass == runnable;
            this.delegate = ListenableFutureTask.create(runnable, value);
            this.someClass = someClass;
        }
        
        private MyRunnableFutureD(SomeClass someClass, Callable<T> callable) {
            assert someClass == callable;
            this.delegate = ListenableFutureTask.create(callable);
            this.someClass = someClass;
        }

        @Override
        protected ListenableFuture<T> delegate() {
            return delegate;
        }

        public void run() {
            System.out.println("MyRunnableFuture.run");
            try {
                delegate.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            System.out.println("MyRunnableFuture.cancel " + someClass.getName());
            return super.cancel(mayInterruptIfRunning);
        }
    }

    public MyListeningExecutorServiceD() {
        // Same as Executors.newSingleThreadExecutor for now
        super(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    }

    @Override
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        if (runnable instanceof SomeClass) {
            return new MyRunnableFutureD<T>((SomeClass) runnable, runnable, value);
        } else {
            return new FutureTask<T>(runnable, value);
        }
    }

    @Override
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        if (callable instanceof SomeClass) {
            return new MyRunnableFutureD<T>((SomeClass) callable, callable);
        } else {
            return new FutureTask<T>(callable);
        }
    }

    /** Must override to supply co-variant return type */
    @Override
    public ListenableFuture<?> submit(Runnable task) {
        return (ListenableFuture<?>) super.submit(task);
    }

    /** Must override to supply co-variant return type */
    @Override
    public <T> ListenableFuture<T> submit(Runnable task, T result) {
        return (ListenableFuture<T>) super.submit(task, result);
    }

    /** Must override to supply co-variant return type */
    @Override
    public <T> ListenableFuture<T> submit(Callable<T> task) {
        return (ListenableFuture<T>) super.submit(task);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T07:30:04+00:00Added an answer on May 28, 2026 at 7:30 am

    Based on this question and a couple others discussions I’ve had recently, I’m coming to the conclusion that RunnableFuture/FutureTask is inherently misleading: Clearly you submit a Runnable, and clearly you get a Future back, and clearly the underlying Thread needs a Runnable. But why should a class implement both Runnable and Future? And if it does, which Runnable is it replacing? That’s bad enough already, but then we introduce multiple levels of executors, and things really get out of hand.

    If there’s a solution here, I think it’s going to require treating FutureTask as an implementation detail of AbstractExecutorService. I’d focus instead on splitting the problem into two pieces:

    • I want to conditionally modify the returned Future.
    • I want to conditionally modify the code run by the executor service. (I’m actually not sure whether this is a requirement here, but I’ll cover it in case it is. Even if not, it may help establish the Runnable/Future distinction.)

    (grumble Markdown grumble)

    class MyWrapperExecutor extends ForwardingListeningExecutorService {
      private final ExecutorService delegateExecutor;
    
      @Override public <T> ListenableFuture<T> submit(Callable<T> task) {
        if (callable instanceof SomeClass) {
          // Modify and submit Callable (or just submit the original Callable):
          ListenableFuture<T> delegateFuture =
              delegateExecutor.submit(new MyCallable(callable));
          // Modify Future:
          return new MyWrapperFuture<T>(delegateFuture);
        } else {
          return delegateExecutor.submit(callable);
        }
      }
    
      // etc.
    }
    

    Could that work?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

My ultimate goal is to have a menu that adds a class to the
My ultimate goal is to load controls as plugins, for use as DocumentContent in
My ultimate goal is to allow users to select a file from a dialog
Here is my ultimate goal... to take this xml file.. <?xml version=1.0?> <Songs> <Song>
I am trying to get my head around a LINQ issue. The ultimate goal
I'm working on a project where there is data visualization. My ultimate goal is
This is not a programming question per se, although the ultimate goal is to
The ultimate goal of this project is to send low level input (so that
I have an injection script--a start script--whose ultimate goal is to redirect to a
I have data that I'm taking from an Excel sheet with the ultimate goal

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.