java在OkHttpClient的execute()方法中使用同步块的优点是什么
我正在阅读OkHttp的源代码
以下是RealCall.java
中的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;
例如,如果同时发出三个请求
请求一个将通过,
请求2将引发异常,
请求三将不被执行
无论是否有同步,代码的工作方式都是一样的
那么,他们为什么在那里写同步
# 1 楼答案
在这种情况下,Synchronized通过防止不同线程并发访问对象来确保thread safety
该块中的
if (exectued)
只是检查操作是否已经发生