Okhttp 双任务队列机制

为了完成调度和复用,定义了两个队列分别用做等待队列(readyAsyncCalls )和执行任务(runningAsyncCalls )的队列。这两个队列都是Dispatcher 成员变量。Dispatcher是一个控制执行,控制全部Call的分发和任务的调度、通讯、清理等操作

/** Ready async calls in the order they'll be run. */
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();

/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();

Call代用equeue方法的时候

首先定义

  private int maxRequests = 64;//设置最大执行线程数
  private int maxRequestsPerHost = 5;//Call对应的host最大数目
 synchronized void enqueue(AsyncCall call) {
    if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
      runningAsyncCalls.add(call);
      executorService().execute(call);
    } else {
      readyAsyncCalls.add(call);
    }
  }

方法中执行队列里面不足最大线程数maxRequests而且Call对应的host数目不超过maxRequestsPerHost 的时候,直接把call对象直接推入到执行队列里,并启动线程任务(Call本质是一个Runnable)。反之则加入到等待队列中。Call执行完确定须要在runningAsyncCalls 队列中移除这个线程。那么readyAsyncCalls队列中的线程在何时才会被执行呢。svg

追溯下AsyncCall 线程的执行方法

 @Override protected void execute() {
      boolean signalledCallback = false;
      try {
        Response response = getResponseWithInterceptorChain();//真正的请求
        if (retryAndFollowUpInterceptor.isCanceled()) {
          signalledCallback = true;
         //返回请求成功的结果
          responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
        } else {
          signalledCallback = true;
          //返回请求失败的结果
          responseCallback.onResponse(RealCall.this, response);
        }
      } catch (IOException e) {
        if (signalledCallback) {
          // Do not signal the callback twice!
          Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
        } else {
          eventListener.callFailed(RealCall.this, e);
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
 // 执行操作完毕了以后无论有无异常都会进入到dispactcher的finished方法。
        client.dispatcher().finished(this);
      }
    }
private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
    int runningCallsCount;
    Runnable idleCallback;
    synchronized (this) {
   //call在runningAsyncCalls队列中被移除了,重新计算了目前正在执行的线程数量
      if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
      if (promoteCalls) promoteCalls();//此处重新设置执行任务
      runningCallsCount = runningCallsCount();
      idleCallback = this.idleCallback;
    }

    if (runningCallsCount == 0 && idleCallback != null) {
      idleCallback.run();
    }
  }
 private void promoteCalls() {
    if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
    if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.

    for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
      AsyncCall call = i.next();

      if (runningCallsForHost(call) < maxRequestsPerHost) {//判断call 运行主机数
        i.remove();//移除等待队列任务
        runningAsyncCalls.add(call);//添加到执行任务队列
        executorService().execute(call);//加入线程池执行
      }

      if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity.
    }
  }

在这里对readyAsyncCalls 进行调度的。最终会在readyAsyncCalls 中经过remove操做把元素迭代取出并移除以后加入到runningAsyncCalls的执行队列中执行操做。ArrayDeque 是非线程安全的因此finished在调用promoteCalls 的时候都在synchronized块中执行的。执行等待队列线程固然的前提是runningAsyncCalls 线程数没有超上线,并且等待队列里面有等待的任务。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chen_ShengJie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值