如果执行了太多请求,ExecutorService 一个线程线程池会阻塞队列

ExecutorService one threaded threadpool is blocking the queue if too many requests are executed

我正在使用一个只有一个线程的线程池来通过 Android 中 RecyclerView 中的一个 viewholder 执行一些网络任务(它们需要按顺序执行)。如果我滚动缓慢,它正在工作。但是如果我快速滚动,太多的任务将被推送到队列,我通过调试发现,这完全阻塞了队列。

我已经(大大)简化了我使用单线程线程池的代码:

if (executorService == null) {
    executorService = Executors.newFixedThreadPool(1);
}

executorService.execute(new Runnable() {
    @Override
    public void run() {
        RessourceService.getCoverPage(url, callback);
        while (waiting) {}
    }
});

那么,如果我想在不阻塞队列的情况下按顺序执行网络任务,有什么选择呢?

您尝试过使用newSingleThreadExecutor()

public static ExecutorService newSingleThreadExecutor()

Creates an Executor that uses a single worker thread operating off an unbounded queue.

(Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.)

Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

(代表问题作者发布答案).

问题出在我的代码中的其他地方,而不是问题中发布的代码中。如我的问题所述,我正在通过 recyclerview 的查看器执行请求。快速滚动时,不会加载图像。我发现问题是在回收站视图中看不到某个项目时发生的。这样做的原因是,由于我的 "waiting" 变量为真,请求被锁定。我可以通过将其设为静态并在每次请求之前将其设置为 false 来解决此问题,从而停止另一个查看器中正在进行的请求。

然而,@Jessie Brian Revil 关于使用 newSingleThreadExecutor 的建议非常有道理。不是我的问题的直接解决方案,而是上面代码的合理解决方案(因此接受)。