-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;
例如,如果有三個請求發出在同一時間。
請求一會通過,
請求兩個會拋出異常,
請求三不會執行。
無論是否同步,代碼工作沒有不同!
那麼,爲什麼他們寫在那裏同步?