【OkHttp】OkHttp 源码分析 ( 同步 / 异步 Request 请求执行原理分析 )(二)

简介: 【OkHttp】OkHttp 源码分析 ( 同步 / 异步 Request 请求执行原理分析 )(二)

二、OkHttp 异步 Request 请求源码分析


异步 Request 请求涉及到线程调度 , 比较复杂 ;


OKHttpClient 调用 newCall 获取 RealCall , 然后调用 RealCall 的 enqueue 方法进行异步 Get/Post 请求 , 在该方法中最终调用 OKHttpClient 对象中的 Dispatcher dispatcher 线程调度器 的 enqueue 方法 , 进行异步请求 ;



1、Dispatcher 调度器 enqueue 方法分析


在 Dispatcher 的 enqueue 方法中 , 调用了 findExistingCallWithHost 方法获取 AsyncCall , 然后在方法最后调用了 promoteAndExecute 进行后续执行异步任务操作 ;


/**
 * Policy on when async requests are executed.
 *
 * <p>Each dispatcher uses an {@link ExecutorService} to run calls internally. If you supply your
 * own executor, it should be able to run {@linkplain #getMaxRequests the configured maximum} number
 * of calls concurrently.
 */
public final class Dispatcher {
  void enqueue(AsyncCall call) {
    synchronized (this) {
      readyAsyncCalls.add(call);
      // Mutate the AsyncCall so that it shares the AtomicInteger of an existing running call to
      // the same host.
      if (!call.get().forWebSocket) {
        AsyncCall existingCall = findExistingCallWithHost(call.host());
        if (existingCall != null) call.reuseCallsPerHostFrom(existingCall);
      }
    }
    promoteAndExecute();
  }
  @Nullable private AsyncCall findExistingCallWithHost(String host) {
    for (AsyncCall existingCall : runningAsyncCalls) {
      if (existingCall.host().equals(host)) return existingCall;
    }
    for (AsyncCall existingCall : readyAsyncCalls) {
      if (existingCall.host().equals(host)) return existingCall;
    }
    return null;
  }
}


AsyncCall 继承了 NamedRunnable , NamedRunnable 实现了 Runnable 接口 , AsyncCall 本质是 Runnable ;

final class AsyncCall extends NamedRunnable
public abstract class NamedRunnable implements Runnable



2、Dispatcher 调度器 promoteAndExecute 方法分析


分析 promoteAndExecute 方法 : 将符合条件的调用从 readyAsyncCalls 提升为 runningAsyncCalls , 并且在线程池中调用它们 ; 这些操作必须同步调用 , 因为执行这些调用需要调用用户代码 ;


最终的异步请求执行调用的是 AsyncCall 的 executeOn 方法 ;


 

AsyncCall asyncCall = executableCalls.get(i);
      asyncCall.executeOn(executorService());


Dispatcher | promoteAndExecute 方法源码 :


 

/**
   * Promotes eligible calls from {@link #readyAsyncCalls} to {@link #runningAsyncCalls} and runs
   * them on the executor service. Must not be called with synchronization because executing calls
   * can call into user code.
   *
   * @return true if the dispatcher is currently running calls.
   */
  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 (asyncCall.callsPerHost().get() >= maxRequestsPerHost) continue; // Host max capacity.
        i.remove();
        asyncCall.callsPerHost().incrementAndGet();
        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;
  }




3、AsyncCall 的 executeOn 方法分析


AsyncCall 的 executeOn 方法中 , 主要使用了 传入的 ExecutorService executorService 线程池 , 执行异步请求任务 ;


RealCall $ AsyncCall | executeOn 方法代码 :


final class RealCall implements Call {
  final class AsyncCall extends NamedRunnable {
    /**
     * Attempt to enqueue this async call on {@code executorService}. This will attempt to clean up
     * if the executor has been shut down by reporting the call as failed.
     */
    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);
        transmitter.noMoreExchanges(ioException);
        responseCallback.onFailure(RealCall.this, ioException);
      } finally {
        if (!success) {
          client.dispatcher().finished(this); // This call is no longer running!
        }
      }
    }
  }
}






三、OkHttp 请求时序图参考


image.png




目录
相关文章
|
JSON 网络协议 Java
OkHttp3发送http请求在Java中的使用方法
记录总结一下Http的get请求和post请求的使用方法和问题解决
2193 0
|
3天前
|
人工智能 API 数据安全/隐私保护
阿里云百炼 Coding Plan解析:200元享9万次,新客首月39.9元‌,包月次数不转按量
阿里云百炼 Coding Plan 现只保留 Pro 一档:目录价 200 元/月,含每月 9 万次模型调用额度,新客首月 39.9 元。它以固定月费整合千问、GLM、Kimi、MiniMax 等多家厂商模型,兼容 Claude Code、Cursor 等主流编程工具,额度用完即停、绝不自动转按量,从机制上避免账单失控。额度按 5 小时 6000 次、每周 45000 次、每月 90000 次三层限流,接入只需专属密钥加两条 Base URL。续费五折已于 2026 年 4 月 1 日结束;团队或后端调用应改用 Token Plan。
|
Android开发
【OkHttp】OkHttp Get 和 Post 请求 ( 同步 Get 请求 | 异步 Get 请求 | 同步 Post 请求 | 异步 Post 请求 )(一)
【OkHttp】OkHttp Get 和 Post 请求 ( 同步 Get 请求 | 异步 Get 请求 | 同步 Post 请求 | 异步 Post 请求 )(一)
1476 0
|
3月前
|
人工智能 自然语言处理 API
觉得阿里云大模型价格太高怎么办?四种便宜购买与使用方法分享
本文针对阿里云大模型“能力强但调用成本高”的普遍痛点,梳理了一套可落地的全链路省钱方案。从开通百炼领取超7000万Tokens新人免费额度起步,叠加夜间错峰4折起的Night Plan活动,再搭配Token Plan订阅与AI通用型节省计划,四层优惠叠加后,实际调用成本可降至普通按量付费的三到五成,帮助个人开发者与团队大幅降低大模型落地的综合开支。
1514 18
|
3月前
|
人工智能
阿里云百炼Coding Plan在哪购买?终于找到了
阿里云百炼Coding Plan Pro高级套餐限时抢购,200元/月,含9万次/月调用额度,支持Qwen3、Kimi、GLM等多模型及图片理解,兼容主流编码工具,每日9:30开抢。阿里云Coding Plan官网:https://t.aliyun.com/U/na1clH
|
4月前
|
人工智能 安全 Linux
零门槛搭建云端 AI 编程环境:Linux 服务器 Docker 部署 OpenCode 保姆级教程
在云原生与AI编程深度融合的当下,OpenCode凭借轻量化、浏览器访问、AI辅助编程的特性,成为开发者打造云端开发环境的优选方案。通过Docker容器化部署OpenCode,可在Linux云服务器上快速搭建跨平台、可随时访问的AI编程环境,无需本地安装复杂IDE,随时随地通过浏览器编写、调试代码,结合AI能力大幅提升开发效率。本文将从环境准备、Docker安装、OpenCode部署、配置优化到安全加固,提供保姆级全流程教程,确保零基础用户也能顺利完成部署,打造专属云端AI编程工作台。
627 0
零门槛搭建云端 AI 编程环境:Linux 服务器 Docker 部署 OpenCode 保姆级教程
|
5月前
|
人工智能 API 开发工具
阿里云百炼Coding Plan指南:费用、Token计费、请求规则与使用限制指南
阿里云百炼Coding Plan是专为AI编程打造的订阅服务,目前仅剩Pro高级版(200元/月),含9万次/月请求额度,分层限流(5小时6000次、每周4.5万次)。支持Qwen3.5-plus、Kimi-k2.5、GLM-5等多模型,兼容Cursor、Qwen Code等工具。需用专属sk-sp-密钥接入,不支持退款,每日9:30限量抢购。阿里云CodingPlan 官网:https://t.aliyun.com/U/G7pldC
939 0
|
边缘计算 监控 Java
跨境电商 API 对接避坑指南:亚马逊 SP-API 超时问题的 5 种解决方案(附重试代码模板)
在对接亚马逊 SP-API 时,超时问题常导致订单延迟、库存失败,影响运营。本文总结某 3C 品牌实战经验,详解超时的 3 大根源与 5 大解决方案,涵盖动态超时、重试机制、请求拆分、并发控制与边缘加速,并附可复用 Python 代码,助你将超时率从 20% 降至 1% 以下。
|
6月前
|
数据采集 人工智能 缓存
字节面试官:别再直接让 AI 写代码了,先学会 SDD 规格驱动开发
AI编程虽快,但需求模糊易致代码失控。SDD(规格驱动开发)主张先明确定义目标、边界、行为、约束与验收标准,再让AI编码。对测试开发尤为关键——它将模糊需求转化为可测、可验、可追溯的质量规格,推动测试前置、风险可控、回归有据。
|
10月前
|
人工智能 Apache 开发者
🧨 新年新气象|x-cmd v0.8.3:Apache 2.0、Minimax M2.5、Claude Code 一键切换
X-CMD v0.8.3 正式发布:开源协议升级为 Apache 2.0,minimax 默认模型升至 M2.5,claude 新增 `use` 命令支持全局/项目级默认模型切换,提升多厂商协同效率。