我将在两个服务之间实现超时框架。我正在研究 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
与 ExecutorService
的优缺点。请不要认为这个问题与 ExectuorService vs ThreadPoolExecutor (which is using LinkedBlockingQueue) 重复。 .
阅读上述问题后我有一些疑问,因此发布了此问题。
建议将
ExecutorSevice
与Executors.XXX 方法
结合使用。如果我使用 Executors.XXX() 方法,我是否可以设置 RejectionHandler、BlockingQueue 大小等?如果没有,我是否必须依靠ThreadPoolExecutor
?ExeuctorService
实现的ThreadPoolExecutor
是否提供无界队列?我正在两个服务之间实现Timeout
框架。
这两者之间哪一个是最佳选择?或者我还有其他最佳选择吗?
最佳答案
- It was recommended to use ExecutorSevice with Executors.XXX methods. If I use Executors.XXX() methods, do I have capabilities to set RejectionHandler, BlockingQueue size etc? If not, Do I have to fall back on ThreadPoolExecutor?
不,您不能通过 Executors
指定这些内容工厂方法。不过,看看Executors
的源代码:你会看到它的 newXXX
方法只是包装调用以创建 ThreadPoolExecutor
实例。
因此,使用 Executors
没有特别的优势。 ,除了不必指定许多参数的便利性之外。如果您需要指定这些附加功能,则需要创建 ThreadPoolExecutor
直接实例。
- Does ExeuctorService offers unbounded queue? I am implementing Timeout framework between two services. Which one is best option between these two? Or Do I have other best option (e.g. CountDownLatch etc.)
ExecutorService
是一个接口(interface):它没有为您提供任何实现细节,例如无界队列。
关于java - ThreadPoolExecutor 与 ExecutorService 的服务超时用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33362448/