美文网首页
OkHttp同步请求和异步请求的区别

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

作者: 石器时代小古董 | 来源:发表于2017-09-06 19:45 被阅读0次

如何发起同步和异步请求

OkHttp 的请求实际上由 RealCall 对象发起,RealCall 提供了 execute 函数发起同步请求和 enqueue 函数发起异步请求

同步请求的执行

  1. 首先会判断当前这个 RealCall 对象是否已经在执行,如果是的话会抛出异常
  2. 交给 Dispatch 做统计
  3. 执行 OkHttp 的各个责任链发起真正的请求功能
  4. 等待责任链返回结果
 @Override public Response execute() throws IOException {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    timeout.enter();
    eventListener.callStart(this);
    try {
      client.dispatcher().executed(this);
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } catch (IOException e) {
      e = timeoutExit(e);
      eventListener.callFailed(this, e);
      throw e;
    } finally {
      client.dispatcher().finished(this);
    }
  }

发起异步请求

OkHttp 的异步请求包装成了 AsyncCall 对象,它是一个线程对象,作为内部类声明在 RealCall 中,由 Dispatch 类统计和执行

  1. 判断当前任务是否执行,如果已经在执行抛出一个异常
  2. 构建一个 AsyncCall 对象交给 Dispatch 类管理
@Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
  }

Dispatcher 类中针对异步任务维护了两个队列,一个 readyAsyncCalls (等待执行队列),一个正在执行的任务队列 runningAsyncCalls

  1. 将该任务交给等待执行队列
  2. 调用 promoteAndExecute 执行请求
  /** 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<>();
  
  void enqueue(AsyncCall call) {
    synchronized (this) {
      readyAsyncCalls.add(call);
    }
    promoteAndExecute();
  }

promoteAndExecute

  1. 准备一个可执行的队列
  2. 轮训所有的等待执行队列,取出任务
  3. 当前正在执行的队列是否达到 64 的上限
  4. 是否同时发起了 5 个请求
  5. 如果满足要求,将消息加入可执行队列,和正在执行队列
  6. 从可执行队列中取出消息,通过线程池执行
  private boolean promoteAndExecute() {
    assert (!Thread.holdsLock(this));

    List<AsyncCall> executableCalls = new ArrayList<>();
    boolean isRunning;
    synchronized (this) {
      for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
        AsyncCall asyncCall = i.next();

        if (runningAsyncCalls.size() >= maxRequests) break; // Max capacity.
        if (runningCallsForHost(asyncCall) >= maxRequestsPerHost) continue; // Host max capacity.

        i.remove();
        executableCalls.add(asyncCall);
        runningAsyncCalls.add(asyncCall);
      }
      isRunning = runningCallsCount() > 0;
    }

    for (int i = 0, size = executableCalls.size(); i < size; i++) {
      AsyncCall asyncCall = executableCalls.get(i);
      asyncCall.executeOn(executorService());
    }

    return isRunning;
  }

消息的执行是由 RealCall 中通过线程池发起的

  1. 发起任务执行
  2. 当 finish 时移除任务
    void executeOn(ExecutorService executorService) {
      assert (!Thread.holdsLock(client.dispatcher()));
      boolean success = false;
      try {
        executorService.execute(this);
        success = true;
      } catch (RejectedExecutionException e) {
        InterruptedIOException ioException = new InterruptedIOException("executor rejected");
        ioException.initCause(e);
        eventListener.callFailed(RealCall.this, ioException);
        responseCallback.onFailure(RealCall.this, ioException);
      } finally {
        if (!success) {
          client.dispatcher().finished(this); // This call is no longer running!
        }
      }
    }

相关文章

  • Android知名三方库OKHttp(一) - 基本使用源码分析

    本文目标 搞明白OKHttp的源码同步请求和异步请求基本流程 基本使用 同步请求 异步请求 1.创建okHttpC...

  • OkHttp 异步请求

    在上两篇文章中介绍了OkHttp同步请求以及同步请求的源码分析,其中也提到了OkHttp的同步请求和异步请求的前三...

  • okhttp分析

    okhttp使用分为同步请求和异步请求:异步请求: request是一个请求对像,包含了请求url,methord...

  • Android-OkHttp 源码解析(拦截器链)

    OkHTTP 中同步请求和异步请求获取 Response 对象都会调用到 getResponseWithInter...

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

    如何发起同步和异步请求 OkHttp 的请求实际上由 RealCall 对象发起,RealCall 提供了 exe...

  • 二十五、OkHttp原理分析(一)

    一、使用方式 OkHttp的使用分为了同步请求和异步请求,分别通过调用execute和enqueue方法,在异步的...

  • Okhttp框架源码分析

    1.OkHttp的简单使用 一般情况下,对于网络框架有两种常见的使用场景,同步请求和异步请求。同步请求: 异步请求...

  • ok小知识点

    1.OKHttp同步和异步的区别 同步:execute()方法 请求网络数据要在子线程中完成操作,然后...

  • 高级知识点

    1.OKHttp同步和异步的区别 同步:execute()方法 请求网络数据要在子线程中完成操作,然后...

  • OkHttp源码解析 -- 同步异步处理

    前言: 使用OkHttp,执行网络请求时会有异步还是同步处理。先说下异步和同步的区别,同步并不是指在UI线程中执行...

网友评论

      本文标题:OkHttp同步请求和异步请求的区别

      本文链接:https://www.haomeiwen.com/subject/njbvjxtx.html