ThreadPoolExecutor与ExecutorService的服务超时用例

时间:2015-10-27 07:51:48

标签: java multithreading executorservice java.util.concurrent threadpoolexecutor

我将在两个服务之间实现Timeout框架。我正在寻找专业人士ThreadPoolExecutor VS ExecutorService

的利弊

使用ExecutorService编写代码。

        ExecutorService service = Executors.newFixedThreadPool(10);
        for ( int i=0; i<10; i++){
            MyCallable myCallable = new MyCallable((long)i);
            Future<Long> futureResult = service.submit(myCallable);
            Long result = null;
            try{
                result = futureResult.get(5000, TimeUnit.MILLISECONDS);
            }catch(TimeoutException e){
                System.out.println("Time out after 5 seconds");
                futureResult.cancel(true);
            }catch(InterruptedException ie){
                System.out.println("Error: Interrupted");
            }catch(ExecutionException ee){
                System.out.println("Error: Execution interrupted");
            }
            System.out.println("Result:"+result);
        }
        service.shutdown();

MyCallable的代码段

class MyCallable implements Callable{
    Long id = 0L;

    public MyCallable(Long val){
        this.id = val;
    }

    public Long call(){
        // **Call a service and get id from the service**
        return id;
    }
}

如果我想用ThreadPoolExecutor实现,我将以这种方式编码

/* Thread pool Executor */
    BlockingQueue queue = new ArrayBlockingQueue(300);
    ThreadPoolExecutor eventsExecutor =
            new ThreadPoolExecutor(1, 10, 60,
                    TimeUnit.SECONDS, queue, new MyRejectionHandler());
/* I can submit the tasks as for above code example used in future */

现在我正在寻找专业人士使用ThreadPoolExecutor Vs ExecutorService的缺点。请不要认为此问题与ExectuorService vs ThreadPoolExecutor (which is using LinkedBlockingQueue)重复。

在阅读上述问题后我有一些疑问,因此发布了这个问题。

  1. 建议ExecutorSeviceExecutors.XXX methods一起使用。如果我使用Executors.XXX()方法,我是否有能力设置RejectionHandlerBlockingQueue大小等?如果没有,我是否必须回到ThreadPoolExecutor

  2. ThreadPoolExecutor实施的ExeuctorService是否提供无限制队列?我正在两个服务之间实现Timeout框架。

  3. 哪一个是这两者之间的最佳选择?或者我还有其他最佳选择吗?

1 个答案:

答案 0 :(得分:1)

  
      
  1. 建议将ExecutorSevice与Executors.XXX方法一起使用。如果我使用Executors.XXX()方法,我是否有能力设置RejectionHandler,BlockingQueue大小等?如果没有,我是否必须依靠ThreadPoolExecutor?
  2.   

不,您无法通过Executors工厂方法指定这些内容。但是,请查看Executors的源代码:您将看到其newXXX方法只是将调用包装到创建ThreadPoolExecutor实例。

因此,除了不必指定许多参数的便利之外,使用Executors没有特别的优势。如果需要指定这些附加功能,则需要直接创建ThreadPoolExecutor实例。

  
      
  1. ExeuctorService是否提供无界队列?我正在两个服务之间实现Timeout框架。哪一个是这两者之间的最佳选择?或者我还有其他最佳选择(例如CountDownLatch等)
  2.   

ExecutorService是一个接口:它通过实现细节(如无界队列)为您提供任何内容。