Skip to content

Commit 0bbf441

Browse files
authored
Ensure buffer is released on exception in SocketStream#read (#888)
JAVA-4523
1 parent a17c52e commit 0bbf441

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

driver-core/src/main/com/mongodb/internal/connection/SocketStream.java

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -103,17 +103,21 @@ public void write(final List<ByteBuf> buffers) throws IOException {
103103
@Override
104104
public ByteBuf read(final int numBytes) throws IOException {
105105
ByteBuf buffer = bufferProvider.getBuffer(numBytes);
106-
int totalBytesRead = 0;
107-
byte[] bytes = buffer.array();
108-
while (totalBytesRead < buffer.limit()) {
109-
int bytesRead = inputStream.read(bytes, totalBytesRead, buffer.limit() - totalBytesRead);
110-
if (bytesRead == -1) {
111-
buffer.release();
112-
throw new MongoSocketReadException("Prematurely reached end of stream", getAddress());
106+
try {
107+
int totalBytesRead = 0;
108+
byte[] bytes = buffer.array();
109+
while (totalBytesRead < buffer.limit()) {
110+
int bytesRead = inputStream.read(bytes, totalBytesRead, buffer.limit() - totalBytesRead);
111+
if (bytesRead == -1) {
112+
throw new MongoSocketReadException("Prematurely reached end of stream", getAddress());
113+
}
114+
totalBytesRead += bytesRead;
113115
}
114-
totalBytesRead += bytesRead;
116+
return buffer;
117+
} catch (Exception e) {
118+
buffer.release();
119+
throw e;
115120
}
116-
return buffer;
117121
}
118122

119123
@Override

0 commit comments

Comments
 (0)