2016-09-22 134 views
-1

我正在阅读OkHttp的源代码。
这里是​​在RealCall.javaOkHttpClient的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; 

例如,如果有三个请求发出在同一时间。
请求一会通过,
请求两个会抛出异常,
请求三不会执行。

无论是否同步,代码工作没有不同!

那么,为什么他们写在那里同步?

回答

0

在这种情况下同步确保thread safety通过阻止并发通过不同的线程访问该对象。

if (exectued)在该区块内仅检查动作是否已经发生。

相关问题