我将在两个服务之间实现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)重复。
在阅读上述问题后我有一些疑问,因此发布了这个问题。
建议ExecutorSevice
与Executors.XXX methods
一起使用。如果我使用Executors.XXX()
方法,我是否有能力设置RejectionHandler
,BlockingQueue
大小等?如果没有,我是否必须回到ThreadPoolExecutor
?
ThreadPoolExecutor
实施的ExeuctorService
是否提供无限制队列?我正在两个服务之间实现Timeout
框架。
哪一个是这两者之间的最佳选择?或者我还有其他最佳选择吗?
答案 0 :(得分:1)
- 建议将ExecutorSevice与Executors.XXX方法一起使用。如果我使用Executors.XXX()方法,我是否有能力设置RejectionHandler,BlockingQueue大小等?如果没有,我是否必须依靠ThreadPoolExecutor?
醇>
不,您无法通过Executors
工厂方法指定这些内容。但是,请查看Executors
的源代码:您将看到其newXXX
方法只是将调用包装到创建ThreadPoolExecutor
实例。
因此,除了不必指定许多参数的便利之外,使用Executors
没有特别的优势。如果需要指定这些附加功能,则需要直接创建ThreadPoolExecutor
实例。
- ExeuctorService是否提供无界队列?我正在两个服务之间实现Timeout框架。哪一个是这两者之间的最佳选择?或者我还有其他最佳选择(例如CountDownLatch等)
醇>
ExecutorService
是一个接口:它通过实现细节(如无界队列)为您提供任何内容。