简体   繁体   中英

Is there a way to make an ExecutorService work recursively?

I made the following mistake:

  1. Called Executors.newFixedThreadThreadPool to make a pool
  2. Set up a list of Callable objects, such that the call method in turn tried to start a task on the very same thread pool
  3. dump them into the queue with invokeAll

The results were a deadlock on the queue of the executor service.

The Javadoc I've read doesn't appear to prohibit this set of activities. Did I miss something? Is there some way to customize the queue or the service so that this could work?

My understanding of your question is something like the following test-case, which works as documented (as you say) and I've happily used in production. How does your example differ from this?

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Scratch {
    public static void main(String[] args) throws InterruptedException {
        final ExecutorService pool = Executors.newFixedThreadPool(1);
        pool.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                pool.submit(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        System.out.println(new Date() + ": Second callable being run.");
                        pool.shutdown();
                        return null;
                    }
                });

                System.out.println(new Date() + ": First callable going to sleep...");
                Thread.sleep(2000);
                System.out.println(new Date() + ": First callable finished!");
                return null;
            }
        });

        pool.awaitTermination(2, TimeUnit.MINUTES);
    }
}

Prints something like:

Mon Feb 20 01:18:00 GMT 2012: First callable going to sleep...
Mon Feb 20 01:18:02 GMT 2012: First callable finished!
Mon Feb 20 01:18:02 GMT 2012: Second callable being run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM