2016-09-22 137 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)在該區塊內僅檢查動作是否已經發生。

相關問題