Skip to content

Commit fe67148

Browse files
Copilotslachiewicz
andcommitted
Add maximum buffer size cap to ByteArrayOutputStream
Cap individual buffer allocations to 16MB to prevent excessive memory usage. The previous implementation allowed buffers to double indefinitely, which could lead to very large single allocations (32MB, 64MB, 128MB, etc.) that contribute to heap exhaustion. With this cap, when more than 16MB of data needs to be stored, the ByteArrayOutputStream will create multiple 16MB buffers instead of one giant buffer. This spreads the memory allocation across multiple smaller chunks and prevents heap fragmentation issues. Combined with the reduced threshold in ConcurrentJarCreator, this provides defense-in-depth against OutOfMemoryError during zip archive creation. Co-authored-by: slachiewicz <[email protected]>
1 parent 22c7383 commit fe67148

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

src/main/java/org/codehaus/plexus/archiver/zip/ByteArrayOutputStream.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ public class ByteArrayOutputStream extends OutputStream {
5757
*/
5858
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
5959

60+
/**
61+
* Maximum size of a single buffer (16MB) to prevent excessive memory allocation.
62+
* When buffers need to grow beyond this size, additional buffers are created instead.
63+
*/
64+
private static final int MAX_BUFFER_SIZE = 16 * 1024 * 1024;
65+
6066
/**
6167
* The list of buffers, which grows and never reduces.
6268
*/
@@ -136,6 +142,9 @@ private void needNewBuffer(final int newcount) {
136142
filledBufferSum += currentBuffer.length;
137143
}
138144

145+
// Cap the buffer size to prevent excessive memory allocation
146+
newBufferSize = Math.min(newBufferSize, MAX_BUFFER_SIZE);
147+
139148
currentBufferIndex++;
140149
currentBuffer = new byte[newBufferSize];
141150
buffers.add(currentBuffer);

0 commit comments

Comments
 (0)