/// <summary> Acquires the read lock unless <see cref="System.Threading.Thread.Interrupt()"/> is called on the current thread</summary> /// <remarks> /// <p/> /// Acquires the read lock if the write lock is not held /// by another thread and returns immediately. /// /// <p/> /// If the write lock is held by another thread then the /// current thread becomes disabled for thread scheduling /// purposes and lies dormant until one of two things happens: /// /// <ul> /// <li>The read lock is acquired by the current thread</li> /// <li>Some other thread calls <see cref="System.Threading.Thread.Interrupt()"/> on the current thread.</li> /// </ul> /// /// <p/>If <see cref="System.Threading.Thread.Interrupt()"/> is called on the current thread, /// a <see cref="System.Threading.ThreadInterruptedException"/> is thrown /// /// <p/> /// In this implementation, as this method is an explicit /// interruption point, preference is given to responding to /// the interrupt over normal or reentrant acquisition of the /// lock. /// </remarks> /// <exception cref="System.Threading.ThreadInterruptedException">if the current thread is interrupted.</exception> public override IDisposable LockInterruptibly() { ThreadInterruptedException ie = null; lock (this) { if (!ReentrantReadWriteLock.StartReadFromNewReader()) { for (;;) { try { Monitor.Wait(this); if (ReentrantReadWriteLock.StartReadFromWaitingReader()) { return(this); } } catch (ThreadInterruptedException ex) { ReentrantReadWriteLock.CancelWaitingReader(); ie = ex; break; } } } } if (ie != null) { ReentrantReadWriteLock.SignallerWriterLock.SignalWaiters(); throw ie; } return(this); }
public void SimpleTest() { var goodThread = new Thread(() => { Console.WriteLine("Good"); Assert.IsFalse(Thread.CurrentThread.IsThreadPoolThread); Assert.IsFalse(Thread.CurrentThread.IsBackground); Assert.IsTrue(Thread.CurrentThread.IsAlive); Assert.IsTrue(Thread.CurrentThread.ApartmentState == ApartmentState.MTA); Assert.IsTrue(Thread.CurrentThread.Priority == ThreadPriority.Normal); Assert.IsTrue(Thread.CurrentThread.ThreadState == ThreadState.Running); ThreadInterruptedException Exception = null; try { Thread.Sleep(5000); } catch (ThreadInterruptedException ex) { Exception = ex; } Assert.IsNotNull(Exception); }); goodThread.Start(); Thread.Sleep(50); goodThread.Interrupt(); }
/// <summary> /// Make by force tokens available for offer. /// </summary> /// <param name="tokens"> /// Specifies the number of tokens that will be made by force available for offer. Defaults to 1. /// </param> /// <exception cref="System.Threading.ThreadInterruptedException"> /// Thrown when a releasing thread is interrupted. /// </exception> public void ForceRelease(uint tokens = 1) { // TIE variable set to null. Needed in case a thread is interrupted while attempting to force release a token in the Semaphore ThreadInterruptedException ex = null; // Infinite post test loop to ensure the designated number of tokens is released while (true) { try { // Release the tokens Release(tokens); // If the TIE variable references a valid TIE, interrupt the current thread if (ex != null) { Thread.CurrentThread.Interrupt(); } // Tokens have been released so return return; } catch (ThreadInterruptedException e) { // A thread has been interrupted so assign our TIE variable to the thrown TIE ex = e; } } }
private static void MultiThreading() { Console.WriteLine("Insert a number or zero to exit:"); number = Convert.ToInt32(Console.ReadLine()); Thread.CurrentThread.Name = "main thread"; mainThreadName = Thread.CurrentThread.Name; newThread = new Thread(Background_do) { Name = "new thread" }; newThread.Start(); Go(); ThreadInterruptedException exception = new ThreadInterruptedException(); newThread.Join(); Console.WriteLine("#############"); foreach (var action in actionsList) { Console.WriteLine(action); } Console.ReadKey(); }
/// <summary> /// Event notification called if the daemon's thread get interrupted. /// </summary> /// <param name="e"> /// <b>ThreadInterruptedException</b>. /// </param> /// <seealso cref="Stop"/> protected virtual void OnInterrupt(ThreadInterruptedException e) { if (!IsExiting) { CacheFactory.Log("Interrupted " + GetType().Name + ", " + Thread.CurrentThread, CacheFactory.LogLevel.Always); } }
/// <summary> /// Acquires the write lock if it is not held by another thread /// within the given waiting time and <see cref="System.Threading.Thread.Interrupt()"/> has not been called on the current thread /// </summary> /// <remarks> /// Acquires the write lock if neither the read nor write lock /// are held by another thread /// and returns immediately with the value <see lang="true"/>, /// setting the write lock hold count to one. If this lock has been /// set to use a fair ordering policy then an available lock /// <b>will not</b> be acquired if any other threads are /// waiting for the write lock. This is in contrast to the <see cref="Spring.Threading.Locks.WriterLock.TryLock()"/> /// If you want a timed <see cref="Spring.Threading.Locks.WriterLock.TryLock()"/> /// that does permit barging on a fair lock, then combine the /// timed and un-timed forms together: /// /// <code> /// if (lock.TryLock() || lock.tryLock(timeSpan) ) { ... } /// </code> /// /// <p/> /// If the current thread already holds this lock then the /// hold count is incremented by one and the method returns /// <see lang="true"/>. /// /// <p/> /// If the lock is held by another thread then the current /// thread becomes disabled for thread scheduling purposes and /// lies dormant until one of three things happens: /// /// <ul> /// <li>The write lock is acquired by the current thread</li> /// <li>Some other thread calls <see cref="System.Threading.Thread.Interrupt()"/> /// on the current thread</li> /// <li>The specified <see cref="System.TimeSpan"/> elapses</li> /// </ul> /// /// <p/> /// If the write lock is acquired then the value <see lang="true"/> is /// returned and the write lock hold count is set to one. /// /// <p/> /// If the current thread has <see cref="System.Threading.Thread.Interrupt()"/> called on it while acquiring /// the write lock, then a <see cref="System.Threading.ThreadInterruptedException"/> is thrown. /// /// <p/> /// If the specified <see cref="System.TimeSpan"/> elapses then the value /// <see lang="false"/> is returned. If the time is less than or /// equal to zero, the method will not wait at all. /// /// <p/> /// In this implementation, as this method is an explicit /// interruption point, preference is given to responding to /// the interrupt over normal or reentrant acquisition of the /// lock, and over reporting the elapse of the waiting time. /// /// </remarks> /// <param name="durationToWait">the time to wait for the write lock</param> /// <returns> <see lang="true"/> if the lock was free and was acquired /// by the current thread, or the write lock was already held by the /// current thread; and <see lang="false"/> if the waiting time /// elapsed before the lock could be acquired. /// </returns> /// /// <exception cref="System.Threading.ThreadInterruptedException">if the current thread is interrupted.</exception> public override bool TryLock(TimeSpan durationToWait) { ThreadInterruptedException ie = null; lock (this) { if (durationToWait.TotalMilliseconds <= 0) { return(ReentrantReadWriteLock.StartWrite()); } else if (ReentrantReadWriteLock.StartWriteFromNewWriter()) { return(true); } else { DateTime deadline = DateTime.Now.Add(durationToWait); for (;;) { try { Monitor.Wait(this, durationToWait); } catch (ThreadInterruptedException ex) { ReentrantReadWriteLock.CancelWaitingWriter(); Monitor.Pulse(this); ie = ex; break; } if (ReentrantReadWriteLock.StartWriteFromWaitingWriter()) { return(true); } else { if (deadline.Subtract(DateTime.Now).TotalMilliseconds <= 0) { ReentrantReadWriteLock.CancelWaitingWriter(); Monitor.Pulse(this); break; } } } } } ReentrantReadWriteLock.SignallerReaderLock.SignalWaiters(); if (ie != null) { throw ie; } else { return(false); } }
/** * Tries to cancel on interrupt; if so rethrowing, * else setting interrupt state * * PRE: lock owned */ private void CheckCancellationOnInterrupt(ThreadInterruptedException ie) { if (_state == 0) { _state = Cancel; Monitor.Pulse(this); throw SystemExtensions.PreserveStackTrace(ie); } Thread.CurrentThread.Interrupt(); }
/** * Tries to cancel on interrupt; if so rethrowing, * else setting interrupt state * * PRE: lock owned */ private void CheckCancellationOnInterrupt(ThreadInterruptedException ie) { if (_state == 0) { _state = Cancel; Monitor.Pulse(_lock); throw ie; } Thread.CurrentThread.Interrupt(); }
/* sei que o master is locked by me*/ public void Pulse() { ThreadInterruptedException tie = enterMon(_cond); Monitor.Enter(_cond); //Não pode falhar porque não pode estar a lancar excepcoes de cancelamento Monitor.Pulse(_cond); Monitor.Exit(_cond); if (tie != null) { Thread.CurrentThread.Interrupt(); } }
private static void EnterWithDelayedInterrupts(Object obj, ThreadInterruptedException interrupt) { for (;;) { try { Monitor.Enter(obj); break; } catch (ThreadInterruptedException ex) { if (interrupt == null) { interrupt = ex; } } } if (interrupt != null) { throw interrupt; } }
private ThreadInterruptedException enterMon(Object mon) { ThreadInterruptedException tie = null; while (true) { try { Monitor.Enter(mon); return(tie); } catch (ThreadInterruptedException e) { tie = e; } } }
[Test] public void InvokeAllOrFailChokesWhenCallFailed([Values(true, false)] bool isTimed) { _actionOnExecute = r => ThreadManager.StartAndAssertRegistered("T", r.Run); var expectedException = new Exception(); _calls[0].Stub(c => c()).Do( new Func <T>( delegate { Thread.Sleep(Delays.Short); throw expectedException; })); ThreadInterruptedException call1Interrupted = null; _calls[1].Stub(c => c()).Do( new Func <T>( delegate { call1Interrupted = Assert.Throws <ThreadInterruptedException>( () => Thread.Sleep(Delays.Small)); return(default(T)); })); for (int i = 2; i < _size; i++) { _calls[i].Stub(c => c()).Return(TestData <T> .MakeData(i)); } var e = Assert.Throws <ExecutionException>( delegate { if (isTimed) { _sut.InvokeAllOrFail(Delays.Small, _calls); } else { _sut.InvokeAllOrFail(_calls); } }); ThreadManager.JoinAndVerify(); // this ensures memeory barrier so we can assert below. Assert.That(e.InnerException, Is.SameAs(expectedException)); Assert.That(call1Interrupted, Is.Not.Null); _calls[2].AssertWasCalled(c => c()); }
public void UninterruptibleLock() { ThreadInterruptedException tie = null; while (true) { try { Monitor.Enter(_lock); break; } catch (ThreadInterruptedException e) { tie = e; } if (tie != null) { Thread.CurrentThread.Interrupt(); } } }
public void ReceiveOrSend_GivenTheThreadIsAbortedBeforePreparationCompletes_JustThrowsTheException() { // Arrange preparationInlet.Setup(p => p.Send(It.IsAny <string>())).Throws <ThreadInterruptedException>(); // Act ThreadInterruptedException exception = null; try { valve.ReceiveOrSend("Not gonna make it..."); } catch (ThreadInterruptedException e) { exception = e; } // Assert preparationInlet.Verify(p => p.Send(It.IsAny <string>()), Times.Once); resultOutlet.Verify(r => r.Receive(), Times.Never); exception.Should().NotBeNull(); }
/// <summary> /// Acquires the write lock unless <see cref="System.Threading.Thread.Interrupt()"/> is called on the current thread /// </summary> /// <remarks> /// Acquires the write lock if neither the read nor write locks /// are held by another thread /// and returns immediately, setting the write lock hold count to /// one. /// /// <p/> /// If the current thread already holds this lock then the /// hold count is incremented by one and the method returns /// immediately. /// /// <p/> /// If the lock is held by another thread then the current /// thread becomes disabled for thread scheduling purposes and /// lies dormant until one of two things happens: /// /// <ul> /// <li>The write lock is acquired by the current thread.</li> /// <li>Some other thread calls <see cref="System.Threading.Thread.Interrupt()"/> on the current thread.</li> /// </ul> /// /// <p/> /// If the write lock is acquired by the current thread then the /// lock hold count is set to one. /// /// <p/> /// If the current thread: /// <ul> /// <li>has its interrupted status set on entry to this method</li> /// <li><see cref="System.Threading.Thread.Interrupt()"/> is called on the thread while acquiring the write lock.</li> /// </ul> /// /// then a <see cref="System.Threading.ThreadInterruptedException"/> is thrown and the current /// thread's interrupted status is cleared. /// /// <p/> /// In this implementation, as this method is an explicit /// interruption point, preference is given to responding to /// the interrupt over normal or reentrant acquisition of the /// lock. /// /// </remarks> /// <exception cref="System.Threading.ThreadInterruptedException">if the current thread is interrupted.</exception> public override IDisposable LockInterruptibly() { ThreadInterruptedException ie = null; lock (this) { if (!ReentrantReadWriteLock.StartWriteFromNewWriter()) { for (;;) { try { Monitor.Wait(this); if (ReentrantReadWriteLock.StartWriteFromWaitingWriter()) { return(this); } } catch (ThreadInterruptedException ex) { ReentrantReadWriteLock.CancelWaitingWriter(); Monitor.Pulse(this); ie = ex; break; } } } } if (ie != null) { // Fall through outside synch on interrupt. // On exception, we may need to signal readers. // It is not worth checking here whether it is strictly necessary. ReentrantReadWriteLock.SignallerReaderLock.SignalWaiters(); throw ie; } return(this); }
public void ReceiveOrSend_GivenThereIsNeitherASenderNorAReceiver_BlocksIndefinitely() { // Act ThreadInterruptedException exception = null; var thread = ThreadHelpers.RunInThread(() => { try { valvedPipe.Valve.ReceiveOrSend("Hello"); } catch (ThreadInterruptedException e) { exception = e; } }); Thread.Sleep(1000); thread.Interrupt(); Thread.Sleep(500); // Assert exception.Should().NotBeNull(); }
public void ReceiveOrSend_GivenTheThreadIsAbortedDuringReceivingAResult_FlushesTheMessageToBeSentAndThrowsTheException() { // Arrange resultOutlet.Setup(r => r.Receive()).Throws <ThreadInterruptedException>(); // Act ThreadInterruptedException exception = null; try { valve.ReceiveOrSend("Not gonna make it..."); } catch (ThreadInterruptedException e) { exception = e; } // Assert preparationInlet.Verify(p => p.Send(It.IsAny <string>()), Times.Once); resultOutlet.Verify(r => r.Receive(), Times.Once); flushOutlet.Verify(f => f.ReceiveImmediately(), Times.Once); exception.Should().NotBeNull(); }
public void SaveSettings_Throws_Exception_When_Serialization_Fails() { // Arrange var testException = new ThreadInterruptedException(); var testBundle = new SettingsManagerTestBundle(); Exception thrownException = null; testBundle.MockSettingsRepository.Setup(x => x.Save(It.IsAny <SettingsRoot>())).Throws(testException); // Act try { testBundle.SettingsManager.SaveSettings(); } catch (Exception ex) { thrownException = ex; } // Assert testBundle.MockSemaphore.Verify(x => x.WaitOne(), Times.Once); testBundle.MockSemaphore.Verify(x => x.Release(), Times.Once); Assert.IsNotNull(thrownException); }
/// <summary> Main exchange function, handling the different policy variants.</summary> private object doExchange(Object objectToExchange, bool timed, TimeSpan duration) { lock (_lock) { TimeSpan durationToWait = duration; object other; DateTime deadline = timed ? DateTime.Now.Add(duration): new DateTime(0); while (_arrivalCount == 2) { if (!timed) { Monitor.Wait(_lock); } else if (durationToWait.Ticks > 0) { Monitor.Wait(_lock, durationToWait); durationToWait = deadline.Subtract(DateTime.Now); } else { throw new TimeoutException("Timeout waiting for other thread."); } } int count = ++_arrivalCount; // If item is already waiting, replace it and signal other thread if (count == 2) { other = _itemToBeExchanged; _itemToBeExchanged = objectToExchange; Monitor.Pulse(_lock); return(other); } // Otherwise, set item and wait for another thread to // replace it and signal us. _itemToBeExchanged = objectToExchange; ThreadInterruptedException interrupted = null; try { while (_arrivalCount != 2) { if (!timed) { Monitor.Wait(_lock); } else if (durationToWait.Ticks > 0) { Monitor.Wait(_lock, durationToWait); durationToWait = deadline.Subtract(DateTime.Now); } else { break; // timed out } } } catch (ThreadInterruptedException ie) { interrupted = ie; } // Get and reset item and count after the wait. // (We need to do this even if wait was aborted.) other = _itemToBeExchanged; _itemToBeExchanged = null; count = _arrivalCount; _arrivalCount = 0; Monitor.Pulse(_lock); // If the other thread replaced item, then we must // continue even if cancelled. if (count == 2) { if (interrupted != null) { Thread.CurrentThread.Interrupt(); } return(other); } // If no one is waiting for us, we can back out if (interrupted != null) { throw interrupted; } // must be timeout throw new TimeoutException(); } }
public virtual void InterruptedWhileShuttingDownjobExecutor(ThreadInterruptedException e) { LogWarn("010", "Interrupted while shutting down the job executor", e); }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="Apache.Http.HttpException"></exception> public virtual CloseableHttpResponse Execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext context, HttpExecutionAware execAware) { Args.NotNull(route, "HTTP route"); Args.NotNull(request, "HTTP request"); Args.NotNull(context, "HTTP context"); ConnectionRequest connRequest = connManager.RequestConnection(route, null); if (execAware != null) { if (execAware.IsAborted()) { connRequest.Cancel(); throw new RequestAbortedException("Request aborted"); } else { execAware.SetCancellable(connRequest); } } RequestConfig config = context.GetRequestConfig(); HttpClientConnection managedConn; try { int timeout = config.GetConnectionRequestTimeout(); managedConn = connRequest.Get(timeout > 0 ? timeout : 0, TimeUnit.Milliseconds); } catch (Exception interrupted) { Sharpen.Thread.CurrentThread().Interrupt(); throw new RequestAbortedException("Request aborted", interrupted); } catch (ExecutionException ex) { Exception cause = ex.InnerException; if (cause == null) { cause = ex; } throw new RequestAbortedException("Request execution failed", cause); } ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn ); try { if (execAware != null) { if (execAware.IsAborted()) { releaseTrigger.Close(); throw new RequestAbortedException("Request aborted"); } else { execAware.SetCancellable(releaseTrigger); } } if (!managedConn.IsOpen()) { int timeout = config.GetConnectTimeout(); this.connManager.Connect(managedConn, route, timeout > 0 ? timeout : 0, context); this.connManager.RouteComplete(managedConn, route, context); } int timeout_1 = config.GetSocketTimeout(); if (timeout_1 >= 0) { managedConn.SetSocketTimeout(timeout_1); } HttpHost target = null; IHttpRequest original = request.GetOriginal(); if (original is IHttpUriRequest) { URI uri = ((IHttpUriRequest)original).GetURI(); if (uri.IsAbsolute()) { target = new HttpHost(uri.GetHost(), uri.GetPort(), uri.GetScheme()); } } if (target == null) { target = route.GetTargetHost(); } context.SetAttribute(HttpClientContext.HttpTargetHost, target); context.SetAttribute(HttpClientContext.HttpRequest, request); context.SetAttribute(HttpClientContext.HttpConnection, managedConn); context.SetAttribute(HttpClientContext.HttpRoute, route); httpProcessor.Process(request, context); HttpResponse response = requestExecutor.Execute(request, managedConn, context); httpProcessor.Process(response, context); // The connection is in or can be brought to a re-usable state. if (reuseStrategy.KeepAlive(response, context)) { // Set the idle duration of this connection long duration = keepAliveStrategy.GetKeepAliveDuration(response, context); releaseTrigger.SetValidFor(duration, TimeUnit.Milliseconds); releaseTrigger.MarkReusable(); } else { releaseTrigger.MarkNonReusable(); } // check for entity, release connection if possible HttpEntity entity = response.GetEntity(); if (entity == null || !entity.IsStreaming()) { // connection not needed and (assumed to be) in re-usable state releaseTrigger.ReleaseConnection(); return(Proxies.EnhanceResponse(response, null)); } else { return(Proxies.EnhanceResponse(response, releaseTrigger)); } } catch (ConnectionShutdownException ex) { ThreadInterruptedException ioex = new ThreadInterruptedException("Connection has been shut down" ); Sharpen.Extensions.InitCause(ioex, ex); throw ioex; } catch (HttpException ex) { releaseTrigger.AbortConnection(); throw; } catch (IOException ex) { releaseTrigger.AbortConnection(); throw; } catch (RuntimeException ex) { releaseTrigger.AbortConnection(); throw; } }
public ZKInterruptedException(ThreadInterruptedException ex) : base(ex) { Thread.CurrentThread.Interrupt(); }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="Apache.Http.HttpException"></exception> public virtual CloseableHttpResponse Execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext context, HttpExecutionAware execAware) { Args.NotNull(route, "HTTP route"); Args.NotNull(request, "HTTP request"); Args.NotNull(context, "HTTP context"); AuthState targetAuthState = context.GetTargetAuthState(); if (targetAuthState == null) { targetAuthState = new AuthState(); context.SetAttribute(HttpClientContext.TargetAuthState, targetAuthState); } AuthState proxyAuthState = context.GetProxyAuthState(); if (proxyAuthState == null) { proxyAuthState = new AuthState(); context.SetAttribute(HttpClientContext.ProxyAuthState, proxyAuthState); } if (request is HttpEntityEnclosingRequest) { Proxies.EnhanceEntity((HttpEntityEnclosingRequest)request); } object userToken = context.GetUserToken(); ConnectionRequest connRequest = connManager.RequestConnection(route, userToken); if (execAware != null) { if (execAware.IsAborted()) { connRequest.Cancel(); throw new RequestAbortedException("Request aborted"); } else { execAware.SetCancellable(connRequest); } } RequestConfig config = context.GetRequestConfig(); HttpClientConnection managedConn; try { int timeout = config.GetConnectionRequestTimeout(); managedConn = connRequest.Get(timeout > 0 ? timeout : 0, TimeUnit.Milliseconds); } catch (Exception interrupted) { Sharpen.Thread.CurrentThread().Interrupt(); throw new RequestAbortedException("Request aborted", interrupted); } catch (ExecutionException ex) { Exception cause = ex.InnerException; if (cause == null) { cause = ex; } throw new RequestAbortedException("Request execution failed", cause); } context.SetAttribute(HttpClientContext.HttpConnection, managedConn); if (config.IsStaleConnectionCheckEnabled()) { // validate connection if (managedConn.IsOpen()) { this.log.Debug("Stale connection check"); if (managedConn.IsStale()) { this.log.Debug("Stale connection detected"); managedConn.Close(); } } } ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn ); try { if (execAware != null) { execAware.SetCancellable(connHolder); } HttpResponse response; for (int execCount = 1; ; execCount++) { if (execCount > 1 && !Proxies.IsRepeatable(request)) { throw new NonRepeatableRequestException("Cannot retry request " + "with a non-repeatable request entity." ); } if (execAware != null && execAware.IsAborted()) { throw new RequestAbortedException("Request aborted"); } if (!managedConn.IsOpen()) { this.log.Debug("Opening connection " + route); try { EstablishRoute(proxyAuthState, managedConn, route, request, context); } catch (TunnelRefusedException ex) { if (this.log.IsDebugEnabled()) { this.log.Debug(ex.Message); } response = ex.GetResponse(); break; } } int timeout = config.GetSocketTimeout(); if (timeout >= 0) { managedConn.SetSocketTimeout(timeout); } if (execAware != null && execAware.IsAborted()) { throw new RequestAbortedException("Request aborted"); } if (this.log.IsDebugEnabled()) { this.log.Debug("Executing request " + request.GetRequestLine()); } if (!request.ContainsHeader(AUTH.WwwAuthResp)) { if (this.log.IsDebugEnabled()) { this.log.Debug("Target auth state: " + targetAuthState.GetState()); } this.authenticator.GenerateAuthResponse(request, targetAuthState, context); } if (!request.ContainsHeader(AUTH.ProxyAuthResp) && !route.IsTunnelled()) { if (this.log.IsDebugEnabled()) { this.log.Debug("Proxy auth state: " + proxyAuthState.GetState()); } this.authenticator.GenerateAuthResponse(request, proxyAuthState, context); } response = requestExecutor.Execute(request, managedConn, context); // The connection is in or can be brought to a re-usable state. if (reuseStrategy.KeepAlive(response, context)) { // Set the idle duration of this connection long duration = keepAliveStrategy.GetKeepAliveDuration(response, context); if (this.log.IsDebugEnabled()) { string s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.Milliseconds; } else { s = "indefinitely"; } this.log.Debug("Connection can be kept alive " + s); } connHolder.SetValidFor(duration, TimeUnit.Milliseconds); connHolder.MarkReusable(); } else { connHolder.MarkNonReusable(); } if (NeedAuthentication(targetAuthState, proxyAuthState, route, response, context)) { // Make sure the response body is fully consumed, if present HttpEntity entity = response.GetEntity(); if (connHolder.IsReusable()) { EntityUtils.Consume(entity); } else { managedConn.Close(); if (proxyAuthState.GetState() == AuthProtocolState.Success && proxyAuthState.GetAuthScheme () != null && proxyAuthState.GetAuthScheme().IsConnectionBased()) { this.log.Debug("Resetting proxy auth state"); proxyAuthState.Reset(); } if (targetAuthState.GetState() == AuthProtocolState.Success && targetAuthState.GetAuthScheme () != null && targetAuthState.GetAuthScheme().IsConnectionBased()) { this.log.Debug("Resetting target auth state"); targetAuthState.Reset(); } } // discard previous auth headers IHttpRequest original = request.GetOriginal(); if (!original.ContainsHeader(AUTH.WwwAuthResp)) { request.RemoveHeaders(AUTH.WwwAuthResp); } if (!original.ContainsHeader(AUTH.ProxyAuthResp)) { request.RemoveHeaders(AUTH.ProxyAuthResp); } } else { break; } } if (userToken == null) { userToken = userTokenHandler.GetUserToken(context); context.SetAttribute(HttpClientContext.UserToken, userToken); } if (userToken != null) { connHolder.SetState(userToken); } // check for entity, release connection if possible HttpEntity entity_1 = response.GetEntity(); if (entity_1 == null || !entity_1.IsStreaming()) { // connection not needed and (assumed to be) in re-usable state connHolder.ReleaseConnection(); return(Proxies.EnhanceResponse(response, null)); } else { return(Proxies.EnhanceResponse(response, connHolder)); } } catch (ConnectionShutdownException ex) { ThreadInterruptedException ioex = new ThreadInterruptedException("Connection has been shut down" ); Sharpen.Extensions.InitCause(ioex, ex); throw ioex; } catch (HttpException ex) { connHolder.AbortConnection(); throw; } catch (IOException ex) { connHolder.AbortConnection(); throw; } catch (RuntimeException ex) { connHolder.AbortConnection(); throw; } }