【发布时间】:2019-07-12 03:10:31
【问题描述】:
我的应用程序依赖 eBay Picture Service 将图像从我的桌面上传到 eBay 服务器。通常,上传完成需要几秒钟。但是,有时可能需要数小时,有时可能永远无法完成。什么时候会发生这种情况是不可预测的,并且 API 不会抛出异常。这会导致我的应用程序同时调用外部 API 太多次,并且还会占用系统资源。
我的目标是设置上传超时,如果在时限内上传不成功,则取消底层进程。我尝试在ExecutorService 上设置超时,然后在this 和this 帖子中建议抛出异常时取消future:
ExecutorService executorService = Executors.newFixedThreadPool(10);
ArrayList<Future<?>> futuresList = new ArrayList<Future<?>>();
for (String singleTask : taskList) {
futuresList.add(executorService.submit( new Runnable(){
@Override
public void run(){
try {
myBlockingTask(singleTask);
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}));
}
try {
future.get(240, TimeUnit.SECONDS);
} catch (Exception e){
e.printStackTrace();
// Stops parent thread from waiting for child but it does not terminate 'child' thread.
// As a result, call(s) to external API continue to increase (rapidly) since the underlying process never actually ends
future.cancel(true);
}
不幸的是,此解决方案仅在底层线程由于无限循环而继续运行和/或底层操作旨在理解Thread.isInterrupted()(如在while() 循环中)时才有效。但是,在这种情况下,我无法控制底层进程,因此我无法在子线程中调用中断。 API 也不提供超时方法。
在这个例子中,有没有办法强制阻塞操作终止?
谢谢!
【问题讨论】:
标签: java multithreading sdk timeout ebay-api