okhttp enqueue流程,字节跳动+阿里+华为+小米等10家大厂面试真题

okhttp enqueue流程,字节跳动+阿里+华为+小米等10家大厂面试真题,第1张

okhttp enqueue流程,字节跳动+阿里+华为+小米等10家大厂面试真题

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

if (runningAsyncCalls.size() >= maxRequests) break; // Max capacity.
最大同时运行数请求为64个。超过就退出循环
if (asyncCall.callsPerHost().get() >= maxRequestsPerHost) continue; // Host max capacity.
每个服务器最大运行请求数位为5 个。超过就结束接下来 *** 作

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;
}

接下来看 asyncCall.executeOn(executorService());每个异步请求被封装成asyncCall

final class AsyncCall extends NamedRunnable {

}
public abstract class NamedRunnable implements Runnable {
protected final String name;

public NamedRunnable(String format, Object… args) {
this.name = Util.format(format, args);
}

@Override public final void run() {
String oldName = Thread.currentThread().getName();
Thread.currentThread().setName(name);
try {
run方法中执行execute,
execute();
} finally {
Thread.currentThread().setName(oldName);
}
}

protected abstract void execute();
}

void executeOn(ExecutorService executorService) {
assert (!Thread.holdsLock(client.dispatcher()));
boolean success = false;
try {
executorService.execute(this);
此处会在线程池中执行AsyncCall 的run方法,即执行 AsyncCall 的execute方法 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!
}
}
}

@Override protected void execute() {
boolean signalledCallback = false;
transmitter.timeoutEnter();
try {
//此处执行上篇文章介绍的 同步请求的方法,加入拦截器,并请求服务器。
Response response = getResponseWithInterceptorChain();
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 {
//失败回调
responseCallback.onFailure(RealCall.this, e);
}
} catch (Throwable t) {
cancel();
if (!signalledCallback) {
IOException canceledException = new IOException("canceled due to " + t);
canceledException.addSuppressed(t);
//失败回调
edException = new IOException("canceled due to " + t);
canceledException.addSuppressed(t);
//失败回调

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5708533.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存