当前位置: 动力学知识库 > 问答 > 编程问答 >

executorservice - Executerservice submits task invokes code after time out

问题描述:

I have below code, the doTransaction method is getting invoked after 20 seconds, could any one tell me why its taking that long to invoke doTransaction method.

Its not happening always its happening very rarely. Any help on this is appreciated.

Thanks,

 ExecutorService service = Executors.newSingleThreadExecutor();

TransactionTask task = new TransactionTask(object);

Future<Result> future = service.submit(task);

Result r = future.get(20000, TimeUnit.MILLISECONDS);

class TransactionTask implements Callable<Result> {

private Request req = null;

public TransactionTask(Request trx){

this.req = trx;

}

@Override

public Result call() throws Exception {

Result o = doTransaction(req);

return o;

}

}

网友答案:

The above behavior could be explained if you submit multiple tasks.

The ExecutorService you created is single threaded, so it could only execute only one task concurrently. Other tasks if submitted will be in queue and will start executing if the former task is terminated/completed

It executes only after 20 seconds because in future.get(20000, TimeUnit.MILLISECONDS); you cancel the already running task. Could you check that you are not getting CancellationException.

Edit: Since you are using Tomcat which is concurrent in execution, I would suggest, you use multithread instead of single thread if not necessary:- Executors.newFixedThreadPool(N); for having N tasks executing concurrently and increase the timout

分享给朋友:
您可能感兴趣的文章:
随机阅读: