From 050f2eceff1659026f84e2d2b57ac3ed317e31ae Mon Sep 17 00:00:00 2001 From: Flavia Rainone Date: Mon, 12 Feb 2024 01:55:50 -0300 Subject: [PATCH] [UNDERTOW-2344] Take into account that close could run concurrently with a read operation Signed-off-by: Flavia Rainone --- .../servlet/spec/ServletInputStreamImpl.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/servlet/src/main/java/io/undertow/servlet/spec/ServletInputStreamImpl.java b/servlet/src/main/java/io/undertow/servlet/spec/ServletInputStreamImpl.java index f8eaa452a6..e470ef911c 100644 --- a/servlet/src/main/java/io/undertow/servlet/spec/ServletInputStreamImpl.java +++ b/servlet/src/main/java/io/undertow/servlet/spec/ServletInputStreamImpl.java @@ -194,10 +194,9 @@ public int read(final byte[] b, final int off, final int len) throws IOException return copied; } - private void readIntoBuffer() throws IOException { + private PooledByteBuffer readIntoBuffer() throws IOException { if (pooled == null && !anyAreSet(state, FLAG_FINISHED)) { - pooled = bufferPool.allocate(); - + final PooledByteBuffer buffer = pooled = bufferPool.allocate(); int res = Channels.readBlocking(channel, pooled.getBuffer()); pooled.getBuffer().flip(); if (res == -1) { @@ -205,7 +204,9 @@ private void readIntoBuffer() throws IOException { pooled.close(); pooled = null; } + return buffer; } + return null; } private void readIntoBufferNonBlocking() throws IOException { @@ -263,7 +264,12 @@ public void close() throws IOException { setFlags(FLAG_CLOSED); try { while (allAreClear(state, FLAG_FINISHED)) { - readIntoBuffer(); + // read is always supposed to run from the same thread, but + // close is a different story... specially in tests + PooledByteBuffer buffer = readIntoBuffer(); + if (buffer != null) { + buffer.close(); + } if (pooled != null) { pooled.close(); pooled = null;