From baf1da473c5c190115df6f1b80cc6834f22f95e5 Mon Sep 17 00:00:00 2001 From: Vladimir Zhilin Date: Sat, 28 Nov 2026 23:27:50 +0100 Subject: [PATCH] Release a blocked caller when a completion handler throws c86097c57c made a BLOCK read or write that times out (or is interrupted) after the completion thread claimed the handler call wait in awaitHandlerCompletion() until the handler has been called. VectoredIOCompletionHandler set the operation state and notified only after the handler returned, so a throwing handler left the caller waiting forever. Set the state and notify in a finally block. Co-Authored-By: Claude Opus 5.5 --- .../tomcat/util/net/SocketWrapperBase.java | 42 +++-- .../upgrade/TestUpgradeInternalHandler.java | 163 ++++++++++++++++++ webapps/docs/changelog.xml | 4 + 3 files changed, 191 insertions(+), 18 deletions(-) diff --git a/java/org/apache/tomcat/util/net/SocketWrapperBase.java b/java/org/apache/tomcat/util/net/SocketWrapperBase.java index 16f23699b0a3..89727bb05b50 100644 --- a/java/org/apache/tomcat/util/net/SocketWrapperBase.java +++ b/java/org/apache/tomcat/util/net/SocketWrapperBase.java @@ -1358,14 +1358,17 @@ public void completed(Long nBytes, OperationState state) { state.state = currentState; } state.end(); - if (completion && state.handler != null && state.callHandler.compareAndSet(true, false)) { - state.handler.completed(Long.valueOf(state.nBytes), state.attachment); - } - synchronized (state) { - state.completionDone = true; - if (notify) { - state.state = currentState; - state.notify(); + try { + if (completion && state.handler != null && state.callHandler.compareAndSet(true, false)) { + state.handler.completed(Long.valueOf(state.nBytes), state.attachment); + } + } finally { + synchronized (state) { + state.completionDone = true; + if (notify) { + state.state = currentState; + state.notify(); + } } } } else { @@ -1404,14 +1407,17 @@ public void failed(Throwable exc, OperationState state) { state.state = state.isInline() ? CompletionState.ERROR : CompletionState.DONE; } state.end(); - if (state.handler != null && state.callHandler.compareAndSet(true, false)) { - state.handler.failed(exc, state.attachment); - } - synchronized (state) { - state.completionDone = true; - if (notify) { - state.state = state.isInline() ? CompletionState.ERROR : CompletionState.DONE; - state.notify(); + try { + if (state.handler != null && state.callHandler.compareAndSet(true, false)) { + state.handler.failed(exc, state.attachment); + } + } finally { + synchronized (state) { + state.completionDone = true; + if (notify) { + state.state = state.isInline() ? CompletionState.ERROR : CompletionState.DONE; + state.notify(); + } } } } @@ -1726,8 +1732,8 @@ protected final CompletionState vectoredOperation(boolean read, ByteBuffer[] /** * The completion thread has claimed the right to call the handler but has not yet finished doing so. Wait for it to - * finish (it updates the state and notifies once the handler has returned) so that the caller does not return - * before the handler has been called. The caller must hold the monitor for the state. + * finish (it updates the state and notifies once the handler has returned or thrown) so that the caller does not + * return before the handler has been called. The caller must hold the monitor for the state. */ private void awaitHandlerCompletion(OperationState state) { boolean interrupted = false; diff --git a/test/org/apache/coyote/http11/upgrade/TestUpgradeInternalHandler.java b/test/org/apache/coyote/http11/upgrade/TestUpgradeInternalHandler.java index 46b35c64f5b5..1bf4c138b5ad 100644 --- a/test/org/apache/coyote/http11/upgrade/TestUpgradeInternalHandler.java +++ b/test/org/apache/coyote/http11/upgrade/TestUpgradeInternalHandler.java @@ -28,7 +28,10 @@ import java.nio.ByteBuffer; import java.nio.channels.CompletionHandler; import java.nio.charset.StandardCharsets; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import javax.net.SocketFactory; @@ -79,6 +82,55 @@ public void testUpgradeInternal() throws Exception { pw.close(); } + // A blocking read whose completion handler throws must still return. Each of these tests prints the stack trace + // of the expected exception from the container thread that ran the handler. + @Test + public void testBlockingReadCompletedThrowsBeforeTimeout() throws Exception { + // The handler throws while the caller is still in its timed wait + doBlockingReadHandlerThrows(BlockingReadThrowingHandler.Mode.COMPLETED_THROWS, 2000, 0, false, + CompletionState.DONE); + } + + @Test + public void testBlockingReadCompletedThrowsAfterTimeout() throws Exception { + // The read times out while the handler (claimed by the completion thread) is still running, so the caller + // waits for the handler to finish; the handler then throws + doBlockingReadHandlerThrows(BlockingReadThrowingHandler.Mode.COMPLETED_THROWS, 200, 1000, false, + CompletionState.ERROR); + } + + @Test + public void testBlockingReadFailedThrows() throws Exception { + // End of stream: the completion thread calls failed(), which throws + doBlockingReadHandlerThrows(BlockingReadThrowingHandler.Mode.FAILED_THROWS, 2000, 0, true, + CompletionState.DONE); + } + + private void doBlockingReadHandlerThrows(BlockingReadThrowingHandler.Mode mode, long readTimeoutMillis, + long handlerDelayMillis, boolean endOfStream, CompletionState expected) throws Exception { + BlockingReadThrowingHandler.reset(mode, readTimeoutMillis, handlerDelayMillis); + UpgradeConnection uc = doUpgrade(BlockingReadThrowingHandler.class); + try { + Assert.assertTrue(BlockingReadThrowingHandler.readStarting.await(10, TimeUnit.SECONDS)); + // Give the read time to register with the poller so that it does not complete inline + Thread.sleep(100); + if (endOfStream) { + uc.shutdownOutput(); + } else { + uc.getWriter().write('x'); + uc.getWriter().flush(); + } + + Assert.assertTrue("Blocking read did not return after the completion handler threw", + BlockingReadThrowingHandler.readReturned.await(10, TimeUnit.SECONDS)); + Assert.assertTrue("The completion handler was not called", + BlockingReadThrowingHandler.handlerCalled.get()); + Assert.assertEquals(expected, BlockingReadThrowingHandler.readState.get()); + } finally { + uc.close(); + } + } + private UpgradeConnection doUpgrade( Class upgradeHandlerClass) throws Exception { // Setup Tomcat instance @@ -183,6 +235,10 @@ public void shutdownOutput() throws IOException { public void shutdownInput() throws IOException { socket.shutdownInput(); } + + public void close() throws IOException { + socket.close(); + } } @@ -283,4 +339,111 @@ public void setSslSupport(SSLSupport sslSupport) { } } + + public static class BlockingReadThrowingHandler implements InternalHttpUpgradeHandler { + + enum Mode { + COMPLETED_THROWS, + FAILED_THROWS + } + + private static volatile Mode mode; + private static volatile long readTimeoutMillis; + private static volatile long handlerDelayMillis; + private static volatile CountDownLatch readStarting; + private static volatile CountDownLatch readReturned; + private static final AtomicBoolean handlerCalled = new AtomicBoolean(); + private static final AtomicReference readState = new AtomicReference<>(); + + private SocketWrapperBase wrapper; + + static void reset(Mode mode, long readTimeoutMillis, long handlerDelayMillis) { + BlockingReadThrowingHandler.mode = mode; + BlockingReadThrowingHandler.readTimeoutMillis = readTimeoutMillis; + BlockingReadThrowingHandler.handlerDelayMillis = handlerDelayMillis; + readStarting = new CountDownLatch(1); + readReturned = new CountDownLatch(1); + handlerCalled.set(false); + readState.set(null); + } + + @Override + public void init(WebConnection connection) { + final ByteBuffer buffer = ByteBuffer.allocate(1024); + try { + readStarting.countDown(); + readState.set(wrapper.read(BlockingMode.BLOCK, readTimeoutMillis, TimeUnit.MILLISECONDS, null, null, + new CompletionHandler() { + @Override + public void completed(Long result, Void attachment) { + if (mode == Mode.COMPLETED_THROWS) { + throwExpectedFailure(); + } + } + + @Override + public void failed(Throwable exc, Void attachment) { + if (mode == Mode.FAILED_THROWS) { + throwExpectedFailure(); + } + } + }, buffer)); + } finally { + readReturned.countDown(); + } + } + + private static void throwExpectedFailure() { + handlerCalled.set(true); + if (handlerDelayMillis > 0) { + try { + Thread.sleep(handlerDelayMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + throw new IllegalStateException("Expected failure in the completion handler"); + } + + @Override + public void pause() { + // NO-OP + } + + @Override + public void destroy() { + // NO-OP + } + + @Override + public SocketState upgradeDispatch(SocketEvent status) { + switch (status) { + case OPEN_READ: + case OPEN_WRITE: + break; + case STOP: + case DISCONNECT: + case ERROR: + case TIMEOUT: + case CONNECT_FAIL: + return SocketState.CLOSED; + } + return SocketState.UPGRADED; + } + + @Override + public void timeoutAsync(long now) { + // NO-OP + } + + @Override + public void setSocketWrapper(SocketWrapperBase wrapper) { + this.wrapper = wrapper; + } + + @Override + public void setSslSupport(SSLSupport sslSupport) { + // NO-OP + } + } } diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index 93ecd8cfe214..4eb02117defb 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -522,6 +522,10 @@ waiting to be processed continues to count towards the limit on the number of concurrent streams until that work has been processed. (markt) + + Ensure that a blocking read or write using asynchronous I/O does not + wait indefinitely if its completion handler throws an exception. +