I am going to implement Timeout framework between two services. I am looking at pros & cons of ThreadPoolExecutor
VS ExecutorService
Code with 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();
Code snippet for 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;
}
}
If I want to implement with ThreadPoolExecutor
, I will code in this way
/* 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 */
Now I am looking at pros & cons of using ThreadPoolExecutor
Vs ExecutorService
. Please don't think that this question is duplicate of ExectuorService vs ThreadPoolExecutor (which is using LinkedBlockingQueue).
I have some queries after reading above question and hence posted this question.
It was recommended to use
ExecutorSevice
withExecutors.XXX methods
. If I useExecutors.XXX()
methods, do I have capabilities to setRejectionHandler
,BlockingQueue
size etc? If not, Do I have to fall back onThreadPoolExecutor
?Does
ThreadPoolExecutor
implemented byExeuctorService
offers unbounded queue? I am implementingTimeout
framework between two services.
Which one is best option between these two? Or Do I have other best option ?