【问题标题】:How to Timeout a Thread Blocking on File Upload When Using 3rd Party Library使用 3rd 方库时如何在文件上传时超时线程阻塞
【发布时间】:2019-07-12 03:10:31
【问题描述】:

我的应用程序依赖 eBay Picture Service 将图像从我的桌面上传到 eBay 服务器。通常,上传完成需要几秒钟。但是,有时可能需要数小时,有时可能永远无法完成。什么时候会发生这种情况是不可预测的,并且 API 不会抛出异常。这会导致我的应用程序同时调用外部 API 太多次,并且还会占用系统资源。

我的目标是设置上传超时,如果在时限内上传不成功,则取消底层进程。我尝试在ExecutorService 上设置超时,然后在thisthis 帖子中建议抛出异常时取消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


    【解决方案1】:

    首先,我建议您进行线程转储,以便找到挂起的确切位置。同时尝试查看您使用的库的源代码,以了解可能导致此挂起的原因。库很可能调用了不负责中断的东西。幸运的是,这样的操作并不多,而且大多数都与套接字 I/O 有关。我见过的关于 JDK 的最全面的列表出现在“Java Concurrency in Practice”一书的第 7.1.6 章中。 Socket I/O 看起来像是对您的情况的合理解释,因为客户端库肯定会通过 HTTP 调用 ebay API。如果它使用标准 JDK HTTP 客户端,请尝试设置these timeouts。否则唯一可能的解决方案是更改库的源代码以使其负责中断或使用另一个:)

    【讨论】:

      猜你喜欢
      • 2013-11-16
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2019-08-28
      相关资源
      最近更新 更多