OkHttp同步请求和异步请求的区别

OKhttp中请求任务的管理是由dispatcher来负责的,负责请求的分发的发起。实际执行请求的是ConnctionPool

同步请求

同一时刻只能有一个任务发起,synchronized关键字锁住了整个代码,那么如果当前OkhttpClient已经执行了一个同步任务,如果这个任务没有释放锁,那么新发起的请求将被阻塞,直到当前任务释放锁


  @Override public Response execute() throws IOException {
    //同一时刻只能有一个任务执行 因为是阻塞式的 由synchronized关键字锁住
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    try {
      client.dispatcher().executed(this);
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } finally {
      client.dispatcher().finished(this);
    }
  }

异步请求

同一时刻可以发起多个请求,因为异步请求每一个都是在一个独立的线程,由两个队列管理,并且synchronized只锁住了代码校验是否执行的部分。


  @Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    //异步请求同一时刻可以有多个任务执行,由两个队列管理
    captureCallStackTrace();
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
  }

你可能感兴趣的:(OkHttp同步请求和异步请求的区别)