-1
我正在阅读OkHttp的源代码。
这里是在RealCall.java
:OkHttpClient的execute()方法中的同步块的优点是什么
public Response execute() throws IOException {
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 (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
我认为没有什么输精管该代码(没有同步)
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
例如,如果有三个请求发出在同一时间。
请求一会通过,
请求两个会抛出异常,
请求三不会执行。
无论是否同步,代码工作没有不同!
那么,为什么他们写在那里同步?