OkHttp中的ThreadPoolExecutor使用和异步操作的Retrofit的区别

Wik*_*rek 0 java threadpoolexecutor retrofit okhttp

OkHttp 2.0.0-RC1使用Dispatcher中ThreadPoolExecutor定义的:#getExecutorService

executorService = new ThreadPoolExecutor(
  0, Integer.MAX_VALUE,
  60, TimeUnit.SECONDS,
  new LinkedBlockingQueue<Runnable>(),
  Util.threadFactory("OkHttp Dispatcher", false));`
Run Code Online (Sandbox Code Playgroud)

这基本上是实现的Executors#newFixedThreadPool.

另一方面,Executors.newCachedThreadPool平台#defaultHttpExecutor中定义的Retrofit使用归结为:

executorService = new ThreadPoolExecutor(
  0, Integer.MAX_VALUE,
  60, TimeUnit.SECONDS,
  new SynchronousQueue<Runnable>(),
  someThreadFactory);
Run Code Online (Sandbox Code Playgroud)

任何人都有任何想法为什么OkHttp使用Executors#newFixedThreadPool和改造Executors#newCachedThreadPool

Jes*_*son 5

它们都更接近缓存的线程池.前两个参数是最重要的:并发运行的最小线程数和并发运行的最大线程数.如果Retrofit或OkHttp没有做任何工作,他们将不会消耗任何线程.如果他们运行1000个并发作业,他们将消耗1000个线程.

60秒是线程在不再需要之后的生命周期.这是缓存位:线程保持一分钟,以便在新作业进入时,不需要线程分配.

因此,差异归结为SynchronousQueueLinkedBlockingQueue.我更喜欢,LinkedBlockingQueue因为排队线程不需要等待正在运行的线程启动.