2016-09-22 13 views
-1

私はOkHttpのソースコードを読んでいます。ここ
RealCall.javaで​​です:OkHttpClientのexecute()メソッドでsynchronizedブロックの利点は何ですか

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; 
    } 

私は3つの要求を同時に放出がある場合は、このコードに精何も(なし同期)例えば

if (executed) throw new IllegalStateException("Already Executed"); 
executed = true; 

は、存在しないと思います。
要求1が実行され、
要求2が例外をスローします。
リクエスト3は実行されません。

同期しているかどうかにかかわらず、コードは機能しません!

だから、なぜ彼らはそこに同期を書いていますか?

答えて

0

この場合同期すると、と同時にが異なるスレッドによってオブジェクトにアクセスすることを防ぎ、thread safetyを保証します。ブロック内のアクションが既に発生しているかどうかを単に確認しています。

関連する問題