This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-compress.git


The following commit(s) were added to refs/heads/master by this push:
     new 7de80e8d7 Honor Pack200 cache limits and avoid duplicate buffering 
(f001) (#857)
7de80e8d7 is described below

commit 7de80e8d71ab1b757c21545e9b2b7221f161b07b
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 29 17:50:11 2026 -0500

    Honor Pack200 cache limits and avoid duplicate buffering (f001) (#857)
    
    * Add a builder for Pack200CompressorInputStream
    
    Add a Commons IO-style Builder with caching strategy and unpacker
    properties options. Delegate construction to a private Builder
    constructor.
    
    Deprecate configurable constructors while retaining the single-argument
    File and InputStream constructors. Add builder tests and direct tests
    for
    each deprecated constructor.
    
    * Honor Pack200 cache limits and avoid duplicate buffering (f001)
    
    Apply the factory's memory limit to the Pack200 JAR cache and reject
    writes that exceed it with MemoryLimitException. Close the source on
    limit failure, preserve unlimited defaults, and document that the limit
    covers cached JAR bytes rather than total unpacker memory.
    
    Remove the full cache copy when creating its input view while preserving
    mark/reset support.
    
    Introduce AbstractCompressorBuilder to share memory-limit configuration
    across Pack200, XZ, and LZMA builders. Retain and document the XZ and
    LZMA
    setter overrides required for binary compatibility.
    
    Add regression tests for cache boundaries, factory integration, resource
    cleanup, input-view behavior, and shared builder configuration. Update
    Javadoc, site documentation, and release notes.
---
 src/changes/changes.xml                            |   4 +
 .../compressors/AbstractCompressorBuilder.java     |  65 +++++++
 .../compressors/CompressorStreamFactory.java       |   6 +-
 .../lzma/LZMACompressorInputStream.java            |  32 ++--
 .../pack200/InMemoryCachingStreamBridge.java       |  74 +++++++-
 .../pack200/Pack200CompressorInputStream.java      | 191 ++++++++++++++++++---
 .../compressors/pack200/Pack200Strategy.java       |  25 ++-
 .../compressors/xz/XZCompressorInputStream.java    |  35 ++--
 src/site/xdoc/examples.xml                         |   5 +-
 src/site/xdoc/pack200.xml                          |   9 +
 .../compressors/AbstractCompressorBuilderTest.java |  90 ++++++++++
 .../commons/compress/compressors/Pack200Test.java  |  10 +-
 .../pack200/InMemoryCachingStreamBridgeTest.java   | 136 +++++++++++++++
 .../Pack200CompressorInputStreamBuilderTest.java   | 137 +++++++++++++++
 ...Pack200CompressorInputStreamDeprecatedTest.java | 173 +++++++++++++++++++
 ...ack200CompressorInputStreamMemoryLimitTest.java | 163 ++++++++++++++++++
 .../Codec_decodeInts_OutOfMemoryErrorTest.java     |   2 +-
 17 files changed, 1085 insertions(+), 72 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index e400ac1ca..50ef4b3d6 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -136,6 +136,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory, Igor 
Morgenstern">[Pack200] org.apache.commons.compress.harmony.pack200 now throws 
Pack200Exception, IllegalArgumentException, IllegalStateException, instead of 
other runtime exceptions and Error.</action>
       <action type="fix" dev="ppkarwasz" due-to="Raeps">[Pack200] Extract 
duplicate code in org.apache.commons.compress.harmony.pack200.IntList.</action>
       <action type="fix" dev="pkarwasz" due-to="Piotr P. Karwasz">[Pack200] 
Simplify `PackingUtils` by leveraging Commons IO.</action>
+      <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[Pack200] Avoid copying the complete in-memory cache when opening its 
input view.</action>
       <!-- FIX cpio -->
       <action type="fix" dev="ggregory" due-to="Stan, Gary Gregory">[Cpio] 
CpioArchiveEntry now throws ArchiveException instead of Arithmetic 
exception.</action>
       <action type="fix" dev="ggregory" due-to="Stan, Gary Gregory">[Cpio] 
CpioArchiveInputStream.getNextEntry() now throws a MemoryLimitException instead 
of OutOfMemoryError when it can't process input greater than available 
memory.</action>
@@ -240,6 +241,9 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use 
ArchiveException.requireNonNull(T, String).</action>
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use 
CompressException.requireNonNull(Class, T, String).</action>
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use 
CpioArchiveEntry.setTimeMillis(long).</action>
+      <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
Pack200CompressorInputStream.builder() and Builder; deprecate constructors with 
strategy or properties parameters.</action>
+      <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
Pack200CompressorInputStream.Builder.setMemoryLimitKiB(int) and apply the 
CompressorStreamFactory memory limit to the Pack200 JAR cache.</action>
+      <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
AbstractCompressorBuilder to share memory-limit configuration across the 
Pack200, XZ, and LZMA input stream builders.</action>
       <!-- UPDATE -->
       <action type="update" dev="ggregory" due-to="Gary Gregory">Bump 
org.apache.commons:commons-parent from 85 to 107 #707, #752.</action>
       <action type="update" dev="ggregory" due-to="Gary Gregory">Bump 
org.apache.commons:commons-lang3 from 3.18.0 to 3.22.0.</action>
diff --git 
a/src/main/java/org/apache/commons/compress/compressors/AbstractCompressorBuilder.java
 
b/src/main/java/org/apache/commons/compress/compressors/AbstractCompressorBuilder.java
new file mode 100644
index 000000000..185ae8e3d
--- /dev/null
+++ 
b/src/main/java/org/apache/commons/compress/compressors/AbstractCompressorBuilder.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.commons.compress.compressors;
+
+import org.apache.commons.io.build.AbstractStreamBuilder;
+
+/**
+ * Base class for compressor stream builders.
+ *
+ * @param <T> The type of compressor stream to build.
+ * @param <B> The type of the concrete builder subclass.
+ * @since 1.29.0
+ */
+public abstract class AbstractCompressorBuilder<T, B extends 
AbstractCompressorBuilder<T, B>> extends AbstractStreamBuilder<T, B> {
+
+    private int memoryLimitKiB = -1;
+
+    /**
+     * Constructs a new instance.
+     */
+    protected AbstractCompressorBuilder() {
+        // empty
+    }
+
+    /**
+     * Gets the memory limit in kibibytes (KiB).
+     *
+     * @return The memory limit in kibibytes, or {@code -1} for no configured 
limit.
+     */
+    public int getMemoryLimitKiB() {
+        return memoryLimitKiB;
+    }
+
+    /**
+     * Sets the memory limit in kibibytes (KiB).
+     *
+     * <p>
+     * The default is {@code -1}, meaning no configured limit. The memory 
covered by this setting depends on the compressor implementation. See the 
concrete
+     * builder for details.
+     * </p>
+     *
+     * @param memoryLimitKiB The memory limit in kibibytes, or {@code -1} for 
no configured limit.
+     * @return {@code this} instance.
+     */
+    public B setMemoryLimitKiB(final int memoryLimitKiB) {
+        this.memoryLimitKiB = memoryLimitKiB;
+        return asThis();
+    }
+}
diff --git 
a/src/main/java/org/apache/commons/compress/compressors/CompressorStreamFactory.java
 
b/src/main/java/org/apache/commons/compress/compressors/CompressorStreamFactory.java
index 48c3f199f..0ae35af8c 100644
--- 
a/src/main/java/org/apache/commons/compress/compressors/CompressorStreamFactory.java
+++ 
b/src/main/java/org/apache/commons/compress/compressors/CompressorStreamFactory.java
@@ -527,7 +527,9 @@ public CompressorStreamFactory(final boolean 
decompressUntilEOF) {
      * @param decompressUntilEOF if true, decompress until the end of the 
input; if false, stop after the first stream and leave the input position to 
point to
      *                           the next byte after the stream. This setting 
applies to the gzip, bzip2 and XZ formats only.
      * @param memoryLimitInKb    Some streams require allocation of 
potentially significant byte arrays/tables, and they can offer checks to 
prevent OOMs on
-     *                           corrupt files. Set the maximum allowed memory 
allocation in KBs.
+     *                           corrupt files. Set the maximum allowed memory 
allocation in KiB. For Pack200, this limits only the generated JAR bytes
+     *                           cached in memory, excluding unpacker working 
memory, unused buffer capacity, and temporary allocations. A negative value
+     *                           leaves the Pack200 cache unlimited.
      *
      * @since 1.14
      */
@@ -633,7 +635,7 @@ public CompressorInputStream 
createCompressorInputStream(final String name, fina
                 return 
LZMACompressorInputStream.builder().setInputStream(in).setMemoryLimitKiB(memoryLimitInKb).get();
             }
             if (PACK200.equalsIgnoreCase(name)) {
-                return new Pack200CompressorInputStream(in);
+                return 
Pack200CompressorInputStream.builder().setInputStream(in).setMemoryLimitKiB(memoryLimitInKb).get();
             }
             if (SNAPPY_RAW.equalsIgnoreCase(name)) {
                 return new SnappyCompressorInputStream(in);
diff --git 
a/src/main/java/org/apache/commons/compress/compressors/lzma/LZMACompressorInputStream.java
 
b/src/main/java/org/apache/commons/compress/compressors/lzma/LZMACompressorInputStream.java
index 09bb3a6b1..952ba1e22 100644
--- 
a/src/main/java/org/apache/commons/compress/compressors/lzma/LZMACompressorInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/compressors/lzma/LZMACompressorInputStream.java
@@ -22,10 +22,10 @@
 import java.io.InputStream;
 
 import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.compress.compressors.AbstractCompressorBuilder;
 import org.apache.commons.compress.compressors.CompressorInputStream;
 import org.apache.commons.compress.utils.InputStreamStatistics;
 import org.apache.commons.io.IOUtils;
-import org.apache.commons.io.build.AbstractStreamBuilder;
 import org.apache.commons.io.input.BoundedInputStream;
 import org.tukaani.xz.LZMA2Options;
 import org.tukaani.xz.LZMAInputStream;
@@ -42,23 +42,26 @@ public class LZMACompressorInputStream extends 
CompressorInputStream implements
      * Builds a new {@link LZMACompressorInputStream}.
      *
      * <p>
+     * The {@linkplain #setMemoryLimitKiB(int) memory limit} applies to 
estimated working memory and is expressed in kibibytes (KiB). The default is
+     * {@code -1}, meaning no limit. Construction throws {@link 
MemoryLimitException} if the estimated memory usage exceeds the configured 
limit.
+     * </p>
+     *
+     * <p>
      * For example:
      * </p>
      * <pre>{@code
-     * LZMACompressorOutputStream s = LZMACompressorInputStream.builder()
+     * LZMACompressorInputStream s = LZMACompressorInputStream.builder()
      *   .setPath(path)
      *   .get();
      * }
      * </pre>
      *
+     * @since 1.28.0
      * @see #get()
      * @see LZMA2Options
-     * @since 1.28.0
      */
     // @formatter:on
-    public static class Builder extends 
AbstractStreamBuilder<LZMACompressorInputStream, Builder> {
-
-        private int memoryLimitKiB = -1;
+    public static class Builder extends 
AbstractCompressorBuilder<LZMACompressorInputStream, Builder> {
 
         /**
          * Constructs a new instance.
@@ -73,22 +76,23 @@ public LZMACompressorInputStream get() throws IOException {
         }
 
         /**
-         * Sets a working memory threshold in kibibytes (KiB).
+         * {@inheritDoc}
          *
-         * @param memoryLimitKiB Sets a working memory threshold in kibibytes 
(KiB). Processing throws MemoryLimitException if memory use is above this.
-         *                       threshold.
-         * @return {@code this} instance.
+         * <p>
+         * This override preserves the concrete {@code Builder} return type 
for binary compatibility.
+         * </p>
          */
+        @Override
         public Builder setMemoryLimitKiB(final int memoryLimitKiB) {
-            this.memoryLimitKiB = memoryLimitKiB;
+            super.setMemoryLimitKiB(memoryLimitKiB);
             return this;
         }
     }
 
     /**
-     * Constructs a new builder of {@link LZMACompressorOutputStream}.
+     * Constructs a new builder of {@link LZMACompressorInputStream}.
      *
-     * @return A new builder of {@link LZMACompressorOutputStream}.
+     * @return A new builder of {@link LZMACompressorInputStream}.
      * @since 1.28.0
      */
     public static Builder builder() {
@@ -114,7 +118,7 @@ public static boolean matches(final byte[] signature, final 
int length) {
     @SuppressWarnings("resource") // Caller closes
     private LZMACompressorInputStream(final Builder builder) throws 
IOException {
         try {
-            in = new LZMAInputStream(countingStream = 
BoundedInputStream.builder().setInputStream(builder.getInputStream()).get(), 
builder.memoryLimitKiB);
+            in = new LZMAInputStream(countingStream = 
BoundedInputStream.builder().setInputStream(builder.getInputStream()).get(), 
builder.getMemoryLimitKiB());
         } catch (final org.tukaani.xz.MemoryLimitException e) {
             // convert to Commons Compress exception
             throw new MemoryLimitException(e.getMemoryNeeded(), 
e.getMemoryLimit(), (Throwable) e);
diff --git 
a/src/main/java/org/apache/commons/compress/compressors/pack200/InMemoryCachingStreamBridge.java
 
b/src/main/java/org/apache/commons/compress/compressors/pack200/InMemoryCachingStreamBridge.java
index be849464d..0da77c213 100644
--- 
a/src/main/java/org/apache/commons/compress/compressors/pack200/InMemoryCachingStreamBridge.java
+++ 
b/src/main/java/org/apache/commons/compress/compressors/pack200/InMemoryCachingStreamBridge.java
@@ -24,6 +24,9 @@
 import java.io.IOException;
 import java.io.InputStream;
 
+import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.io.IOUtils;
+
 /**
  * StreamBridge that caches all data written to the output side in memory.
  *
@@ -31,12 +34,75 @@
  */
 final class InMemoryCachingStreamBridge extends AbstractStreamBridge {
 
-    InMemoryCachingStreamBridge() {
-        super(new ByteArrayOutputStream());
+    /**
+     * Provides an input view without copying the cached bytes.
+     *
+     * <p>
+     * The JDK {@link ByteArrayOutputStream} exposes its backing array and 
byte count to subclasses, allowing a {@link ByteArrayInputStream} view that
+     * preserves mark/reset support without copying the cached bytes. Commons 
IO's
+     * {@link 
org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream#toInputStream()}
 returns a {@link java.io.SequenceInputStream} for nonempty data.
+     * That view does not support mark/reset. Using {@code toByteArray()} to 
create an input stream with mark/reset support would copy the entire cache.
+     * </p>
+     *
+     * <p>
+     * The enclosing bridge already synchronizes cache writes and creation of 
input views; the JDK stream is used for direct access to its backing array.
+     * </p>
+     */
+    private static final class Cache extends ByteArrayOutputStream {
+
+        /**
+         * Creates an input view of the current contents, excluding any 
subsequent writes.
+         *
+         * @return An input stream with mark and reset support.
+         */
+        InputStream toInputStream() {
+            return new ByteArrayInputStream(buf, 0, count);
+        }
+    }
+
+    private final Cache cache;
+
+    private final int memoryLimitKiB;
+
+    /**
+     * Constructs an in-memory cache with the given size limit.
+     *
+     * @param memoryLimitKiB The maximum number of cached kibibytes, or a 
negative value for no limit.
+     */
+    InMemoryCachingStreamBridge(final int memoryLimitKiB) {
+        super(new Cache());
+        cache = (Cache) out;
+        this.memoryLimitKiB = memoryLimitKiB;
+    }
+
+    /**
+     * Checks the cache size before writing any bytes.
+     *
+     * @param additional The number of bytes to append.
+     * @throws MemoryLimitException if the resulting cache size would exceed 
the limit.
+     */
+    private void checkCacheLimit(final int additional) throws 
MemoryLimitException {
+        final long memoryNeededKiB = ((long) cache.size() + additional + 1023) 
/ 1024;
+        if (memoryLimitKiB >= 0 && memoryNeededKiB > memoryLimitKiB) {
+            throw new MemoryLimitException(memoryNeededKiB, memoryLimitKiB);
+        }
+    }
+
+    @Override
+    synchronized InputStream createInputStream() throws IOException {
+        return cache.toInputStream();
+    }
+
+    @Override
+    public synchronized void write(final byte[] b, final int off, final int 
len) throws IOException {
+        IOUtils.checkFromIndexSize(b, off, len);
+        checkCacheLimit(len);
+        cache.write(b, off, len);
     }
 
     @Override
-    InputStream createInputStream() throws IOException {
-        return new ByteArrayInputStream(((ByteArrayOutputStream) 
out).toByteArray());
+    public synchronized void write(final int b) throws IOException {
+        checkCacheLimit(1);
+        cache.write(b);
     }
 }
diff --git 
a/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStream.java
 
b/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStream.java
index 9744a98c1..fa2bcdfd2 100644
--- 
a/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStream.java
@@ -24,11 +24,16 @@
 import java.io.InputStream;
 import java.io.UncheckedIOException;
 import java.util.Map;
+import java.util.Objects;
 import java.util.jar.JarOutputStream;
 
+import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.compress.compressors.AbstractCompressorBuilder;
 import org.apache.commons.compress.compressors.CompressorInputStream;
 import org.apache.commons.compress.java.util.jar.Pack200;
 import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.build.AbstractOrigin;
+import org.apache.commons.io.build.AbstractOrigin.FileOrigin;
 
 /**
  * An input stream that decompresses from the Pack200 format to be read as any 
other stream.
@@ -37,14 +42,129 @@
  * The {@link CompressorInputStream#getCount getCount} and {@link 
CompressorInputStream#getBytesRead getBytesRead} methods always return 0.
  * </p>
  *
+ * <p>
+ * To build an instance, use {@link Builder}.
+ * </p>
+ *
  * @NotThreadSafe
  * @since 1.3
  */
 public class Pack200CompressorInputStream extends CompressorInputStream {
 
+    // @formatter:off
+    /**
+     * Builds a new {@link Pack200CompressorInputStream}.
+     *
+     * <p>
+     * The {@linkplain #setMemoryLimitKiB(int) memory limit} applies only to 
{@link Pack200Strategy#IN_MEMORY}; {@link Pack200Strategy#TEMP_FILE} is 
unaffected.
+     * The default is {@code -1}. Any negative value means no limit, and zero 
permits no cached bytes.
+     * </p>
+     *
+     * <p>
+     * The limit counts generated JAR bytes cached, including JAR headers and 
possibly compressed entries. It does not limit the unpacker's working memory,
+     * unused buffer capacity, or temporary allocations while the cache grows. 
Unpacking still completes during construction.
+     * </p>
+     *
+     * <p>
+     * If a write would exceed the limit, construction fails with {@link 
MemoryLimitException} and closes the source stream.
+     * </p>
+     *
+     * <p>
+     * For example:
+     * </p>
+     * <pre>{@code
+     * Pack200CompressorInputStream s = Pack200CompressorInputStream.builder()
+     *   .setPath(path)
+     *   .setStrategy(Pack200Strategy.TEMP_FILE)
+     *   .get();}
+     * </pre>
+     *
+     * @since 1.29.0
+     * @see #get()
+     */
+    // @formatter:on
+    public static class Builder extends 
AbstractCompressorBuilder<Pack200CompressorInputStream, Builder> {
+
+        private Map<String, String> properties;
+
+        private Pack200Strategy strategy = Pack200Strategy.IN_MEMORY;
+
+        /**
+         * Constructs a new builder of {@link Pack200CompressorInputStream}.
+         */
+        public Builder() {
+            // empty
+        }
+
+        /**
+         * Builds a new {@link Pack200CompressorInputStream}.
+         *
+         * <p>
+         * You must set input that supports {@link InputStream}, otherwise, 
this method throws an exception.
+         * </p>
+         *
+         * @return A new instance.
+         * @throws IOException                   if reading or caching fails.
+         * @throws MemoryLimitException          if the in-memory cache would 
exceed the configured limit.
+         * @throws IllegalStateException         if the {@code origin} is 
{@code null}.
+         * @throws UnsupportedOperationException if the origin cannot be 
converted to an {@link InputStream}.
+         * @see AbstractOrigin#getInputStream(java.nio.file.OpenOption...)
+         */
+        @Override
+        public Pack200CompressorInputStream get() throws IOException {
+            return new Pack200CompressorInputStream(this);
+        }
+
+        /**
+         * Gets the file to unpack directly, or {@code null} to use an input 
stream.
+         *
+         * @return The file origin when no custom open options are set, 
otherwise {@code null}.
+         */
+        private File getUnpackFile() {
+            return checkOrigin() instanceof FileOrigin && 
getOpenOptions().length == 0 ? getFile() : null;
+        }
+
+        /**
+         * Sets the Pack200 unpacker properties.
+         *
+         * @param properties Pack200 properties to use, or {@code null} to use 
the unpacker's defaults.
+         * @return {@code this} instance.
+         */
+        public Builder setProperties(final Map<String, String> properties) {
+            this.properties = properties;
+            return this;
+        }
+
+        /**
+         * Sets the strategy used to cache the unpacked JAR.
+         *
+         * <p>
+         * The default is {@link Pack200Strategy#IN_MEMORY}.
+         * </p>
+         *
+         * @param strategy The caching strategy, not {@code null}.
+         * @return {@code this} instance.
+         * @throws NullPointerException if {@code strategy} is {@code null}.
+         */
+        public Builder setStrategy(final Pack200Strategy strategy) {
+            this.strategy = Objects.requireNonNull(strategy, "strategy");
+            return this;
+        }
+    }
+
     private static final byte[] CAFE_DOOD = { (byte) 0xCA, (byte) 0xFE, (byte) 
0xD0, (byte) 0x0D };
     private static final int SIG_LENGTH = CAFE_DOOD.length;
 
+    /**
+     * Constructs a new builder of {@link Pack200CompressorInputStream}.
+     *
+     * @return A new builder of {@link Pack200CompressorInputStream}.
+     * @since 1.29.0
+     */
+    public static Builder builder() {
+        return new Builder();
+    }
+
     /**
      * Checks if the signature matches what is expected for a pack200 file 
(0xCAFED00D).
      *
@@ -70,6 +190,32 @@ public static boolean matches(final byte[] signature, final 
int length) {
 
     private final AbstractStreamBridge abstractStreamBridge;
 
+    /**
+     * Constructs a new instance configured by the given builder.
+     *
+     * @param builder The builder.
+     * @throws IOException if reading or caching fails.
+     */
+    private Pack200CompressorInputStream(final Builder builder) throws 
IOException {
+        final File file = builder.getUnpackFile();
+        originalInputStream = file == null ? builder.getInputStream() : null;
+        abstractStreamBridge = 
builder.strategy.newStreamBridge(builder.getMemoryLimitKiB());
+        try (JarOutputStream jarOut = new 
JarOutputStream(abstractStreamBridge)) {
+            final Pack200.Unpacker unpacker = Pack200.newUnpacker();
+            if (builder.properties != null) {
+                unpacker.properties().putAll(builder.properties);
+            }
+            if (file == null) {
+                unpacker.unpack(originalInputStream, jarOut);
+            } else {
+                unpacker.unpack(file, jarOut);
+            }
+        } catch (final MemoryLimitException e) {
+            IOUtils.closeQuietly(originalInputStream);
+            throw e;
+        }
+    }
+
     /**
      * Decompresses the given file, caching the decompressed data in memory.
      *
@@ -77,7 +223,7 @@ public static boolean matches(final byte[] signature, final 
int length) {
      * @throws IOException if reading fails.
      */
     public Pack200CompressorInputStream(final File file) throws IOException {
-        this(file, Pack200Strategy.IN_MEMORY);
+        this(builder().setFile(file));
     }
 
     /**
@@ -86,9 +232,11 @@ public Pack200CompressorInputStream(final File file) throws 
IOException {
      * @param file       The file to decompress.
      * @param properties Pack200 properties to use.
      * @throws IOException if reading fails.
+     * @deprecated Use {@link #builder()}.
      */
+    @Deprecated
     public Pack200CompressorInputStream(final File file, final Map<String, 
String> properties) throws IOException {
-        this(file, Pack200Strategy.IN_MEMORY, properties);
+        this(builder().setFile(file).setProperties(properties));
     }
 
     /**
@@ -97,9 +245,11 @@ public Pack200CompressorInputStream(final File file, final 
Map<String, String> p
      * @param file The file to decompress.
      * @param mode The strategy to use.
      * @throws IOException if reading fails.
+     * @deprecated Use {@link #builder()}.
      */
+    @Deprecated
     public Pack200CompressorInputStream(final File file, final Pack200Strategy 
mode) throws IOException {
-        this(null, file, mode, null);
+        this(builder().setFile(file).setStrategy(mode));
     }
 
     /**
@@ -109,9 +259,11 @@ public Pack200CompressorInputStream(final File file, final 
Pack200Strategy mode)
      * @param mode       The strategy to use.
      * @param properties Pack200 properties to use.
      * @throws IOException if reading fails.
+     * @deprecated Use {@link #builder()}.
      */
+    @Deprecated
     public Pack200CompressorInputStream(final File file, final Pack200Strategy 
mode, final Map<String, String> properties) throws IOException {
-        this(null, file, mode, properties);
+        
this(builder().setFile(file).setStrategy(mode).setProperties(properties));
     }
 
     /**
@@ -125,24 +277,7 @@ public Pack200CompressorInputStream(final File file, final 
Pack200Strategy mode,
      * @throws IOException if reading fails.
      */
     public Pack200CompressorInputStream(final InputStream inputStream) throws 
IOException {
-        this(inputStream, Pack200Strategy.IN_MEMORY);
-    }
-
-    private Pack200CompressorInputStream(final InputStream inputStream, final 
File file, final Pack200Strategy mode, final Map<String, String> properties)
-            throws IOException {
-        this.originalInputStream = inputStream;
-        this.abstractStreamBridge = mode.newStreamBridge();
-        try (JarOutputStream jarOut = new 
JarOutputStream(abstractStreamBridge)) {
-            final Pack200.Unpacker unpacker = Pack200.newUnpacker();
-            if (properties != null) {
-                unpacker.properties().putAll(properties);
-            }
-            if (file == null) {
-                unpacker.unpack(inputStream, jarOut);
-            } else {
-                unpacker.unpack(file, jarOut);
-            }
-        }
+        this(builder().setInputStream(inputStream));
     }
 
     /**
@@ -155,9 +290,11 @@ private Pack200CompressorInputStream(final InputStream 
inputStream, final File f
      * @param inputStream The InputStream from which this object should be 
created.
      * @param properties  Pack200 properties to use.
      * @throws IOException if reading fails.
+     * @deprecated Use {@link #builder()}.
      */
+    @Deprecated
     public Pack200CompressorInputStream(final InputStream inputStream, final 
Map<String, String> properties) throws IOException {
-        this(inputStream, Pack200Strategy.IN_MEMORY, properties);
+        this(builder().setInputStream(inputStream).setProperties(properties));
     }
 
     /**
@@ -170,9 +307,11 @@ public Pack200CompressorInputStream(final InputStream 
inputStream, final Map<Str
      * @param inputStream The InputStream from which this object should be 
created.
      * @param mode        The strategy to use.
      * @throws IOException if reading fails.
+     * @deprecated Use {@link #builder()}.
      */
+    @Deprecated
     public Pack200CompressorInputStream(final InputStream inputStream, final 
Pack200Strategy mode) throws IOException {
-        this(inputStream, null, mode, null);
+        this(builder().setInputStream(inputStream).setStrategy(mode));
     }
 
     /**
@@ -186,9 +325,11 @@ public Pack200CompressorInputStream(final InputStream 
inputStream, final Pack200
      * @param mode        The strategy to use.
      * @param properties  Pack200 properties to use.
      * @throws IOException if reading fails.
+     * @deprecated Use {@link #builder()}.
      */
+    @Deprecated
     public Pack200CompressorInputStream(final InputStream inputStream, final 
Pack200Strategy mode, final Map<String, String> properties) throws IOException {
-        this(inputStream, null, mode, properties);
+        
this(builder().setInputStream(inputStream).setStrategy(mode).setProperties(properties));
     }
 
     @SuppressWarnings("resource") // Does not allocate
diff --git 
a/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200Strategy.java
 
b/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200Strategy.java
index 5b6c4d5d6..f87327abe 100644
--- 
a/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200Strategy.java
+++ 
b/src/main/java/org/apache/commons/compress/compressors/pack200/Pack200Strategy.java
@@ -31,18 +31,35 @@ public enum Pack200Strategy {
     /** Cache output in memory. */
     IN_MEMORY() {
         @Override
-        AbstractStreamBridge newStreamBridge() {
-            return new InMemoryCachingStreamBridge();
+        AbstractStreamBridge newStreamBridge(final int memoryLimitKiB) {
+            return new InMemoryCachingStreamBridge(memoryLimitKiB);
         }
     },
 
     /** Cache output in a temporary file. */
     TEMP_FILE() {
         @Override
-        AbstractStreamBridge newStreamBridge() throws IOException {
+        AbstractStreamBridge newStreamBridge(final int memoryLimitKiB) throws 
IOException {
             return new TempFileCachingStreamBridge();
         }
     };
 
-    abstract AbstractStreamBridge newStreamBridge() throws IOException;
+    /**
+     * Creates an unlimited cache.
+     *
+     * @return A new stream bridge.
+     * @throws IOException if the cache cannot be created.
+     */
+    AbstractStreamBridge newStreamBridge() throws IOException {
+        return newStreamBridge(-1);
+    }
+
+    /**
+     * Creates a cache with the given in-memory size limit.
+     *
+     * @param memoryLimitKiB The maximum number of cached kibibytes, or a 
negative value for no limit. Ignored by {@link #TEMP_FILE}.
+     * @return A new stream bridge.
+     * @throws IOException if the cache cannot be created.
+     */
+    abstract AbstractStreamBridge newStreamBridge(int memoryLimitKiB) throws 
IOException;
 }
diff --git 
a/src/main/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStream.java
 
b/src/main/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStream.java
index b432bef51..6f6d21681 100644
--- 
a/src/main/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStream.java
@@ -22,12 +22,10 @@
 import java.io.InputStream;
 
 import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.compress.compressors.AbstractCompressorBuilder;
 import org.apache.commons.compress.compressors.CompressorInputStream;
-import org.apache.commons.compress.compressors.lzma.LZMACompressorInputStream;
-import org.apache.commons.compress.compressors.lzma.LZMACompressorOutputStream;
 import org.apache.commons.compress.utils.InputStreamStatistics;
 import org.apache.commons.io.IOUtils;
-import org.apache.commons.io.build.AbstractStreamBuilder;
 import org.apache.commons.io.input.BoundedInputStream;
 import org.tukaani.xz.LZMA2Options;
 import org.tukaani.xz.SingleXZInputStream;
@@ -56,7 +54,12 @@ public class XZCompressorInputStream extends 
CompressorInputStream implements In
 
     // @formatter:off
     /**
-     * Builds a new {@link LZMACompressorInputStream}.
+     * Builds a new {@link XZCompressorInputStream}.
+     *
+     * <p>
+     * The {@linkplain #setMemoryLimitKiB(int) memory limit} applies when 
reading blocks and is expressed in kibibytes (KiB). The default is {@code -1},
+     * meaning no limit. Reading throws {@link MemoryLimitException} if the 
estimated memory usage exceeds the configured limit.
+     * </p>
      *
      * <p>
      * For example:
@@ -70,14 +73,13 @@ public class XZCompressorInputStream extends 
CompressorInputStream implements In
      * }
      * </pre>
      *
+     * @since 1.28.0
      * @see #get()
      * @see LZMA2Options
-     * @since 1.28.0
      */
     // @formatter:on
-    public static class Builder extends 
AbstractStreamBuilder<XZCompressorInputStream, Builder> {
+    public static class Builder extends 
AbstractCompressorBuilder<XZCompressorInputStream, Builder> {
 
-        private int memoryLimitKiB = -1;
         private boolean decompressConcatenated;
 
         /**
@@ -105,22 +107,23 @@ public Builder setDecompressConcatenated(final boolean 
decompressConcatenated) {
         }
 
         /**
-         * Sets a working memory threshold in kibibytes (KiB).
+         * {@inheritDoc}
          *
-         * @param memoryLimitKiB The memory limit used when reading blocks. 
The memory usage limit is expressed in kibibytes (KiB) or {@code -1} to impose 
no
-         *                       memory usage limit. If the estimated memory 
limit is exceeded on {@link #read()}, a {@link MemoryLimitException} is thrown.
-         * @return {@code this} instance.
+         * <p>
+         * This override preserves the concrete {@code Builder} return type 
for binary compatibility.
+         * </p>
          */
+        @Override
         public Builder setMemoryLimitKiB(final int memoryLimitKiB) {
-            this.memoryLimitKiB = memoryLimitKiB;
+            super.setMemoryLimitKiB(memoryLimitKiB);
             return this;
         }
     }
 
     /**
-     * Constructs a new builder of {@link LZMACompressorOutputStream}.
+     * Constructs a new builder of {@link XZCompressorInputStream}.
      *
-     * @return A new builder of {@link LZMACompressorOutputStream}.
+     * @return A new builder of {@link XZCompressorInputStream}.
      * @since 1.28.0
      */
     public static Builder builder() {
@@ -157,9 +160,9 @@ public static boolean matches(final byte[] signature, final 
int length) {
     private XZCompressorInputStream(final Builder builder) throws IOException {
         countingStream = 
BoundedInputStream.builder().setInputStream(builder.getInputStream()).get();
         if (builder.decompressConcatenated) {
-            in = new XZInputStream(countingStream, builder.memoryLimitKiB);
+            in = new XZInputStream(countingStream, 
builder.getMemoryLimitKiB());
         } else {
-            in = new SingleXZInputStream(countingStream, 
builder.memoryLimitKiB);
+            in = new SingleXZInputStream(countingStream, 
builder.getMemoryLimitKiB());
         }
     }
 
diff --git a/src/site/xdoc/examples.xml b/src/site/xdoc/examples.xml
index 5ac537fc2..3f4c5fd8a 100644
--- a/src/site/xdoc/examples.xml
+++ b/src/site/xdoc/examples.xml
@@ -98,7 +98,10 @@ CompressorInputStream input = new CompressorStreamFactory()
         constructor argument that can be used to set an upper limit of
         memory that may be used while decompressing or compressing a
         stream. As of 1.14 this setting only affects decompressing Z,
-        XZ and LZMA compressed streams.</p>
+        XZ and LZMA compressed streams. Since 1.29.0 it also limits the
+        generated JAR bytes cached in memory when unpacking Pack200. For 
Pack200,
+        unpacker working memory, unused buffer capacity, and temporary 
allocations
+        are not included in the limit.</p>
         <p>Since Compress 1.19 <code>SevenZFile</code> also has an
         optional constructor to pass an upper memory limit which is supported
         in LZMA compressed streams. Since Compress 1.21 this setting
diff --git a/src/site/xdoc/pack200.xml b/src/site/xdoc/pack200.xml
index a77fbac34..5b574e449 100644
--- a/src/site/xdoc/pack200.xml
+++ b/src/site/xdoc/pack200.xml
@@ -60,6 +60,15 @@
         is cached in memory but you should switch to the temporary
         file option if your archives are really big.</p>
 
+        <p>Since 1.29.0, 
<code>Pack200CompressorInputStream.Builder.setMemoryLimitKiB</code>
+        can limit the size of the generated JAR cached by the in-memory 
strategy.
+        A negative value, including the default of -1, leaves the cache 
unlimited.
+        If a write would exceed the limit, construction throws
+        <code>MemoryLimitException</code> and closes the source stream. The 
limit
+        counts JAR bytes, including headers and possibly compressed entries; it
+        does not bound unpacker working memory, unused buffer capacity, or 
temporary
+        allocations during cache growth. The temporary-file strategy is 
unaffected.</p>
+
         <p>Given there always is an intermediate result
         the <code>getBytesRead</code> and <code>getCount</code>
         methods of <code>Pack200CompressorInputStream</code> are
diff --git 
a/src/test/java/org/apache/commons/compress/compressors/AbstractCompressorBuilderTest.java
 
b/src/test/java/org/apache/commons/compress/compressors/AbstractCompressorBuilderTest.java
new file mode 100644
index 000000000..68f045b0c
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/compressors/AbstractCompressorBuilderTest.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.commons.compress.compressors;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.compress.compressors.lzma.LZMACompressorInputStream;
+import 
org.apache.commons.compress.compressors.pack200.Pack200CompressorInputStream;
+import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
+import org.apache.commons.io.IOUtils;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+/**
+ * Tests shared memory-limit configuration through the concrete compressor 
builders.
+ */
+class AbstractCompressorBuilderTest extends AbstractTest {
+
+    private enum Format {
+
+        LZMA("bla.tar.lzma"), PACK200("bla.pack"), XZ("bla.tar.xz"), 
XZ_CONCATENATED("bla.tar.xz");
+
+        private final String resource;
+
+        Format(final String resource) {
+            this.resource = resource;
+        }
+    }
+
+    private AbstractCompressorBuilder<? extends CompressorInputStream, ?> 
builder(final Format format) throws IOException {
+        final byte[] packed = Files.readAllBytes(getPath(format.resource));
+        switch (format) {
+        case LZMA:
+            return LZMACompressorInputStream.builder().setByteArray(packed);
+        case PACK200:
+            return Pack200CompressorInputStream.builder().setByteArray(packed);
+        default:
+            return 
XZCompressorInputStream.builder().setByteArray(packed).setDecompressConcatenated(format
 == Format.XZ_CONCATENATED);
+        }
+    }
+
+    private byte[] decompress(final AbstractCompressorBuilder<? extends 
CompressorInputStream, ?> builder) throws IOException {
+        try (InputStream input = builder.get()) {
+            return IOUtils.toByteArray(input);
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(Format.class)
+    void testMemoryLimit(final Format format) throws IOException {
+        final AbstractCompressorBuilder<? extends CompressorInputStream, ?> 
builder = builder(format);
+        assertEquals(-1, builder.getMemoryLimitKiB());
+        final byte[] expected = decompress(builder);
+        assertTrue(expected.length > 0);
+        assertSame(builder, builder.setMemoryLimitKiB(0));
+        final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> decompress(builder));
+        assertEquals(0, exception.getMemoryLimitInKb());
+        assertSame(builder, builder.setMemoryLimitKiB(100_000));
+        assertEquals(100_000, builder.getMemoryLimitKiB());
+        assertArrayEquals(expected, decompress(builder));
+        assertSame(builder, builder.setMemoryLimitKiB(-1));
+        assertArrayEquals(expected, decompress(builder));
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/compressors/Pack200Test.java 
b/src/test/java/org/apache/commons/compress/compressors/Pack200Test.java
index c6caaf12f..0e8a164be 100644
--- a/src/test/java/org/apache/commons/compress/compressors/Pack200Test.java
+++ b/src/test/java/org/apache/commons/compress/compressors/Pack200Test.java
@@ -73,8 +73,8 @@ private void jarArchiveCreation(final Pack200Strategy mode) 
throws Exception {
 
     private void jarUnarchiveAll(final boolean useFile, final Pack200Strategy 
mode) throws Exception {
         final File input = getFile("bla.pack");
-        try (InputStream is = useFile ? new 
Pack200CompressorInputStream(input, mode)
-                : new 
Pack200CompressorInputStream(Files.newInputStream(input.toPath()), mode);
+        try (InputStream is = useFile ? 
Pack200CompressorInputStream.builder().setFile(input).setStrategy(mode).get()
+                : 
Pack200CompressorInputStream.builder().setInputStream(Files.newInputStream(input.toPath())).setStrategy(mode).get();
                 ArchiveInputStream<?> in = 
ArchiveStreamFactory.DEFAULT.createArchiveInputStream("jar", is)) {
             in.forEach(entry -> {
                 final File archiveEntry = newTempFile(entry.getName());
@@ -91,7 +91,7 @@ private void jarUnarchiveAll(final boolean useFile, final 
Pack200Strategy mode)
     private void multiByteReadConsistentlyReturnsMinusOneAtEof(final 
Pack200Strategy s) throws Exception {
         final File input = getFile("bla.pack");
         final byte[] buf = new byte[2];
-        try (Pack200CompressorInputStream in = new 
Pack200CompressorInputStream(input, s)) {
+        try (Pack200CompressorInputStream in = 
Pack200CompressorInputStream.builder().setFile(input).setStrategy(s).get()) {
             IOUtils.toByteArray(in);
             assertEquals(-1, in.read(buf));
             assertEquals(-1, in.read(buf));
@@ -100,7 +100,7 @@ private void 
multiByteReadConsistentlyReturnsMinusOneAtEof(final Pack200Strategy
 
     private void singleByteReadConsistentlyReturnsMinusOneAtEof(final 
Pack200Strategy s) throws Exception {
         final File input = getFile("bla.pack");
-        try (Pack200CompressorInputStream in = new 
Pack200CompressorInputStream(input, s)) {
+        try (Pack200CompressorInputStream in = 
Pack200CompressorInputStream.builder().setFile(input).setStrategy(s).get()) {
             IOUtils.toByteArray(in);
             assertEquals(-1, in.read());
             assertEquals(-1, in.read());
@@ -129,7 +129,7 @@ void testGoodSignature() throws Exception {
     void testInputStreamMethods() throws Exception {
         final Map<String, String> m = new HashMap<>();
         m.put("foo", "bar");
-        try (InputStream is = new 
Pack200CompressorInputStream(newInputStream("bla.jar"), m)) {
+        try (InputStream is = 
Pack200CompressorInputStream.builder().setInputStream(newInputStream("bla.jar")).setProperties(m).get())
 {
             // packed file is a jar, which is a ZIP, so it starts with
             // a local file header
             assertTrue(is.markSupported());
diff --git 
a/src/test/java/org/apache/commons/compress/compressors/pack200/InMemoryCachingStreamBridgeTest.java
 
b/src/test/java/org/apache/commons/compress/compressors/pack200/InMemoryCachingStreamBridgeTest.java
new file mode 100644
index 000000000..ca0560d59
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/compressors/pack200/InMemoryCachingStreamBridgeTest.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.commons.compress.compressors.pack200;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.InputStream;
+
+import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.io.IOUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests {@link InMemoryCachingStreamBridge}.
+ */
+class InMemoryCachingStreamBridgeTest {
+
+    @Test
+    void testExactLimit() throws Exception {
+        try (InMemoryCachingStreamBridge bridge = new 
InMemoryCachingStreamBridge(1)) {
+            final byte[] expected = new byte[1024];
+            expected[0] = 42;
+            bridge.write(expected[0]);
+            bridge.write(expected, 1, expected.length - 1);
+            bridge.write(expected, expected.length, 0);
+            final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> bridge.write(1));
+            assertEquals(2, exception.getMemoryNeededInKb());
+            assertEquals(1, exception.getMemoryLimitInKb());
+            assertEquals(1, exception.getMemoryLimitInKiBLong());
+            assertThrows(MemoryLimitException.class, () -> bridge.write(new 
byte[1]));
+            try (InputStream input = bridge.getInputStream()) {
+                assertArrayEquals(expected, IOUtils.toByteArray(input));
+            }
+        }
+    }
+
+    @Test
+    void testInputViewPreservesMarkResetAndSnapshot() throws Exception {
+        try (InMemoryCachingStreamBridge bridge = new 
InMemoryCachingStreamBridge(-1)) {
+            final byte[] expected = new byte[8193];
+            for (int i = 0; i < expected.length; i++) {
+                expected[i] = (byte) i;
+            }
+            bridge.write(expected);
+            try (InputStream input = bridge.getInputStream()) {
+                assertTrue(input.markSupported());
+                input.mark(expected.length);
+                assertEquals(expected.length, input.available());
+                assertEquals(0, input.read());
+                assertEquals(1024, input.skip(1024));
+                input.reset();
+                bridge.write(42);
+                assertArrayEquals(expected, IOUtils.toByteArray(input));
+                assertEquals(-1, input.read());
+            }
+        }
+    }
+
+    @Test
+    void testInvalidWritesDoNotConsumeLimit() throws Exception {
+        try (InMemoryCachingStreamBridge bridge = new 
InMemoryCachingStreamBridge(1)) {
+            final byte[] bytes = new byte[1024];
+            assertThrows(NullPointerException.class, () -> bridge.write(null, 
0, 1));
+            assertThrows(IndexOutOfBoundsException.class, () -> 
bridge.write(bytes, -1, 1));
+            assertThrows(IndexOutOfBoundsException.class, () -> 
bridge.write(bytes, 0, -1));
+            assertThrows(IndexOutOfBoundsException.class, () -> 
bridge.write(bytes, bytes.length, 1));
+            assertThrows(IndexOutOfBoundsException.class, () -> 
bridge.write(bytes, 1, Integer.MAX_VALUE));
+            bridge.write(bytes);
+            try (InputStream input = bridge.getInputStream()) {
+                assertArrayEquals(bytes, IOUtils.toByteArray(input));
+            }
+        }
+    }
+
+    @Test
+    void testRejectedBulkWriteDoesNotConsumeLimit() throws Exception {
+        try (InMemoryCachingStreamBridge bridge = new 
InMemoryCachingStreamBridge(1)) {
+            bridge.write(new byte[1023]);
+            assertThrows(MemoryLimitException.class, () -> bridge.write(new 
byte[2], 0, 2));
+            bridge.write(42);
+            try (InputStream input = bridge.getInputStream()) {
+                final byte[] bytes = IOUtils.toByteArray(input);
+                assertEquals(1024, bytes.length);
+                assertEquals(42, bytes[1023]);
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { -1, -2, Integer.MIN_VALUE, Integer.MAX_VALUE })
+    void testUnrestrictiveLimits(final int limit) throws Exception {
+        try (InMemoryCachingStreamBridge bridge = new 
InMemoryCachingStreamBridge(limit)) {
+            final byte[] bytes = new byte[8193];
+            bridge.write(bytes);
+            try (InputStream input = bridge.getInputStream()) {
+                assertArrayEquals(bytes, IOUtils.toByteArray(input));
+            }
+        }
+    }
+
+    @Test
+    void testZeroLimit() throws Exception {
+        try (InMemoryCachingStreamBridge bridge = new 
InMemoryCachingStreamBridge(0)) {
+            bridge.write(new byte[0]);
+            final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> bridge.write(0));
+            assertEquals(1, exception.getMemoryNeededInKb());
+            assertEquals(0, exception.getMemoryLimitInKb());
+            assertThrows(MemoryLimitException.class, () -> bridge.write(new 
byte[1]));
+            try (InputStream input = bridge.getInputStream()) {
+                assertEquals(-1, input.read());
+            }
+        }
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamBuilderTest.java
 
b/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamBuilderTest.java
new file mode 100644
index 000000000..c995b4905
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamBuilderTest.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.commons.compress.compressors.pack200;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.StandardOpenOption;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.jar.JarOutputStream;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.harmony.unpack200.Pack200UnpackerAdapter;
+import org.apache.commons.io.IOUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junitpioneer.jupiter.SetSystemProperty;
+
+/**
+ * Tests {@link Pack200CompressorInputStream.Builder}.
+ */
+public class Pack200CompressorInputStreamBuilderTest extends AbstractTest {
+
+    /**
+     * Checks that properties are available to the unpacker before unpacking 
begins.
+     */
+    public static class PropertyCheckingUnpacker extends 
Pack200UnpackerAdapter {
+
+        @Override
+        public void unpack(final InputStream in, final JarOutputStream out) 
throws IOException {
+            assertEquals("value", properties().get("test.property"));
+            super.unpack(in, out);
+        }
+    }
+
+    private void assertUnpacked(final Pack200CompressorInputStream.Builder 
builder) throws IOException {
+        try (InputStream expected = new 
Pack200CompressorInputStream(getFile("bla.pack")); InputStream actual = 
builder.get()) {
+            assertArrayEquals(IOUtils.toByteArray(expected), 
IOUtils.toByteArray(actual));
+        }
+    }
+
+    @Test
+    void testBuilderDefaults() throws IOException {
+        assertUnpacked(new 
Pack200CompressorInputStream.Builder().setFile(getFile("bla.pack")));
+    }
+
+    @Test
+    void testBuilderInputStreamClose() throws IOException {
+        final AtomicBoolean closed = new AtomicBoolean();
+        final InputStream input = new 
ByteArrayInputStream(Files.readAllBytes(getFile("bla.pack").toPath())) {
+            @Override
+            public void close() throws IOException {
+                closed.set(true);
+                super.close();
+            }
+        };
+        try (Pack200CompressorInputStream unpacked = 
Pack200CompressorInputStream.builder().setInputStream(input).get()) {
+            assertFalse(closed.get());
+            assertTrue(unpacked.read() >= 0);
+        }
+        assertTrue(closed.get());
+    }
+
+    @Test
+    void testBuilderNoOrigin() {
+        assertThrows(IllegalStateException.class, () -> 
Pack200CompressorInputStream.builder().get());
+    }
+
+    @Test
+    void testBuilderNullProperties() throws IOException {
+        
assertUnpacked(Pack200CompressorInputStream.builder().setFile(getFile("bla.pack"))
+                .setProperties(Collections.singletonMap("test.property", 
"value")).setProperties(null));
+    }
+
+    @Test
+    void testBuilderNullStrategy() {
+        assertThrows(NullPointerException.class, () -> 
Pack200CompressorInputStream.builder().setStrategy(null));
+    }
+
+    @Test
+    void testBuilderOpenOptions() throws IOException {
+        
assertUnpacked(Pack200CompressorInputStream.builder().setFile(getFile("bla.pack")).setOpenOptions(StandardOpenOption.READ));
+    }
+
+    @ParameterizedTest
+    @EnumSource(Pack200Strategy.class)
+    void testBuilderOrigins(final Pack200Strategy strategy) throws IOException 
{
+        final File file = getFile("bla.pack");
+        final byte[] bytes = Files.readAllBytes(file.toPath());
+        
assertUnpacked(Pack200CompressorInputStream.builder().setFile(file).setStrategy(strategy));
+        
assertUnpacked(Pack200CompressorInputStream.builder().setPath(file.toPath()).setStrategy(strategy));
+        
assertUnpacked(Pack200CompressorInputStream.builder().setByteArray(bytes).setStrategy(strategy));
+        
assertUnpacked(Pack200CompressorInputStream.builder().setInputStream(new 
ByteArrayInputStream(bytes)).setStrategy(strategy));
+    }
+
+    @Test
+    @SetSystemProperty(key = "java.util.jar.Pack200.Unpacker",
+            value = 
"org.apache.commons.compress.compressors.pack200.Pack200CompressorInputStreamBuilderTest$PropertyCheckingUnpacker")
+    void testBuilderProperties() throws IOException {
+        final File file = getFile("bla.pack");
+        try (InputStream unpacked = 
Pack200CompressorInputStream.builder().setFile(file)
+                .setProperties(Collections.singletonMap("test.property", 
"value")).get()) {
+            assertTrue(unpacked.read() >= 0);
+        }
+        try (InputStream unpacked = 
Pack200CompressorInputStream.builder().setByteArray(Files.readAllBytes(file.toPath()))
+                .setProperties(Collections.singletonMap("test.property", 
"value")).get()) {
+            assertTrue(unpacked.read() >= 0);
+        }
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamDeprecatedTest.java
 
b/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamDeprecatedTest.java
new file mode 100644
index 000000000..459a0b798
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamDeprecatedTest.java
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.commons.compress.compressors.pack200;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Map;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+import java.util.jar.JarOutputStream;
+import java.util.stream.Stream;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.harmony.unpack200.Pack200UnpackerAdapter;
+import org.apache.commons.io.IOUtils;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junitpioneer.jupiter.SetSystemProperty;
+
+/**
+ * Tests the deprecated {@link Pack200CompressorInputStream} constructors.
+ */
+@Tag("deprecated")
+@SetSystemProperty(key = "java.util.jar.Pack200.Unpacker",
+        value = 
"org.apache.commons.compress.compressors.pack200.Pack200CompressorInputStreamDeprecatedTest$PropertyRecordingUnpacker")
+public class Pack200CompressorInputStreamDeprecatedTest extends AbstractTest {
+
+    /**
+     * Includes the configured property in the output so constructor property 
forwarding can be verified.
+     */
+    public static class PropertyRecordingUnpacker extends 
Pack200UnpackerAdapter {
+
+        @Override
+        public void unpack(final InputStream in, final JarOutputStream out) 
throws IOException {
+            final JarEntry entry = new JarEntry("test.properties");
+            entry.setTime(0);
+            out.putNextEntry(entry);
+            out.write(properties().getOrDefault("test.property", 
"default").getBytes(UTF_8));
+            out.closeEntry();
+            super.unpack(in, out);
+        }
+    }
+
+    /**
+     * Tracks whether the decompressor closes its input stream.
+     */
+    private static class CloseTrackingInputStream extends ByteArrayInputStream 
{
+
+        private boolean closed;
+
+        CloseTrackingInputStream() throws IOException {
+            super(Files.readAllBytes(getFile("bla.pack").toPath()));
+        }
+
+        @Override
+        public void close() throws IOException {
+            closed = true;
+            super.close();
+        }
+    }
+
+    static Stream<Map<String, String>> properties() {
+        return Stream.of(null, Collections.singletonMap("test.property", 
"value"));
+    }
+
+    static Stream<Arguments> strategiesAndProperties() {
+        return Arrays.stream(Pack200Strategy.values()).flatMap(strategy -> 
properties().map(properties -> Arguments.of(strategy, properties)));
+    }
+
+    private void assertUnpacked(final Pack200CompressorInputStream actual, 
final Pack200Strategy strategy, final Map<String, String> properties)
+            throws IOException {
+        try (Pack200CompressorInputStream expected = 
Pack200CompressorInputStream.builder().setFile(getFile("bla.pack")).setStrategy(strategy)
+                .setProperties(properties).get()) {
+            assertEquals(strategy == Pack200Strategy.IN_MEMORY, 
actual.markSupported());
+            final byte[] actualBytes = IOUtils.toByteArray(actual);
+            assertArrayEquals(IOUtils.toByteArray(expected), actualBytes);
+            try (JarInputStream jar = new JarInputStream(new 
ByteArrayInputStream(actualBytes))) {
+                assertEquals("test.properties", 
jar.getNextJarEntry().getName());
+                assertEquals(properties == null ? "default" : 
properties.get("test.property"), IOUtils.toString(jar, UTF_8));
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("properties")
+    void testFileProperties(final Map<String, String> properties) throws 
IOException {
+        try (Pack200CompressorInputStream actual = new 
Pack200CompressorInputStream(getFile("bla.pack"), properties)) {
+            assertUnpacked(actual, Pack200Strategy.IN_MEMORY, properties);
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(Pack200Strategy.class)
+    void testFileStrategy(final Pack200Strategy strategy) throws IOException {
+        try (Pack200CompressorInputStream actual = new 
Pack200CompressorInputStream(getFile("bla.pack"), strategy)) {
+            assertUnpacked(actual, strategy, null);
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("strategiesAndProperties")
+    void testFileStrategyProperties(final Pack200Strategy strategy, final 
Map<String, String> properties) throws IOException {
+        try (Pack200CompressorInputStream actual = new 
Pack200CompressorInputStream(getFile("bla.pack"), strategy, properties)) {
+            assertUnpacked(actual, strategy, properties);
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("properties")
+    void testInputStreamProperties(final Map<String, String> properties) 
throws IOException {
+        try (CloseTrackingInputStream input = new CloseTrackingInputStream()) {
+            try (Pack200CompressorInputStream actual = new 
Pack200CompressorInputStream(input, properties)) {
+                assertFalse(input.closed);
+                assertUnpacked(actual, Pack200Strategy.IN_MEMORY, properties);
+            }
+            assertTrue(input.closed);
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(Pack200Strategy.class)
+    void testInputStreamStrategy(final Pack200Strategy strategy) throws 
IOException {
+        try (CloseTrackingInputStream input = new CloseTrackingInputStream()) {
+            try (Pack200CompressorInputStream actual = new 
Pack200CompressorInputStream(input, strategy)) {
+                assertFalse(input.closed);
+                assertUnpacked(actual, strategy, null);
+            }
+            assertTrue(input.closed);
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("strategiesAndProperties")
+    void testInputStreamStrategyProperties(final Pack200Strategy strategy, 
final Map<String, String> properties) throws IOException {
+        try (CloseTrackingInputStream input = new CloseTrackingInputStream()) {
+            try (Pack200CompressorInputStream actual = new 
Pack200CompressorInputStream(input, strategy, properties)) {
+                assertFalse(input.closed);
+                assertUnpacked(actual, strategy, properties);
+            }
+            assertTrue(input.closed);
+        }
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamMemoryLimitTest.java
 
b/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamMemoryLimitTest.java
new file mode 100644
index 000000000..157756452
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/compressors/pack200/Pack200CompressorInputStreamMemoryLimitTest.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.commons.compress.compressors.pack200;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.compress.compressors.CompressorException;
+import org.apache.commons.compress.compressors.CompressorStreamFactory;
+import org.apache.commons.io.IOUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests the Pack200 in-memory cache limit.
+ */
+class Pack200CompressorInputStreamMemoryLimitTest extends AbstractTest {
+
+    private enum Origin {
+        FILE, PATH, BYTE_ARRAY, INPUT_STREAM
+    }
+
+    private Pack200CompressorInputStream.Builder builder(final Origin origin) 
throws IOException {
+        final File file = getFile("bla.pack");
+        final Pack200CompressorInputStream.Builder builder = 
Pack200CompressorInputStream.builder();
+        switch (origin) {
+        case FILE:
+            return builder.setFile(file);
+        case PATH:
+            return builder.setPath(file.toPath());
+        case BYTE_ARRAY:
+            return builder.setByteArray(Files.readAllBytes(file.toPath()));
+        default:
+            return builder.setInputStream(new 
ByteArrayInputStream(Files.readAllBytes(file.toPath())));
+        }
+    }
+
+    private byte[] unpackedBytes() throws IOException {
+        try (InputStream input = 
Pack200CompressorInputStream.builder().setFile(getFile("bla.pack")).get()) {
+            return IOUtils.toByteArray(input);
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(Origin.class)
+    void testCacheLimit(final Origin origin) throws IOException {
+        final byte[] expected = unpackedBytes();
+        final int requiredKiB = (expected.length + 1023) / 1024;
+        try (InputStream input = 
builder(origin).setProperties(Collections.singletonMap("test.property", 
"value")).setMemoryLimitKiB(requiredKiB).get()) {
+            assertArrayEquals(expected, IOUtils.toByteArray(input));
+        }
+        final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> 
builder(origin).setMemoryLimitKiB(requiredKiB - 1).get());
+        assertEquals(requiredKiB, exception.getMemoryNeededInKb());
+        assertEquals(requiredKiB - 1, exception.getMemoryLimitInKb());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { false, true })
+    void testFactoryLimit(final boolean autoDetect) throws Exception {
+        final byte[] packed = Files.readAllBytes(getFile("bla.pack").toPath());
+        final byte[] expected = unpackedBytes();
+        final int requiredKiB = (expected.length + 1023) / 1024;
+        final CompressorStreamFactory limited = new 
CompressorStreamFactory(false, requiredKiB - 1);
+        final CompressorException exception = 
assertThrows(CompressorException.class, () -> {
+            try (InputStream source = new ByteArrayInputStream(packed);
+                    InputStream input = autoDetect ? 
limited.createCompressorInputStream(source)
+                            : 
limited.createCompressorInputStream(CompressorStreamFactory.PACK200, source)) {
+                input.read();
+            }
+        });
+        final MemoryLimitException cause = 
assertInstanceOf(MemoryLimitException.class, exception.getCause());
+        assertEquals(requiredKiB - 1, cause.getMemoryLimitInKb());
+        for (final int limit : new int[] { -1, requiredKiB, Integer.MAX_VALUE 
}) {
+            final CompressorStreamFactory factory = new 
CompressorStreamFactory(false, limit);
+            try (InputStream source = new ByteArrayInputStream(packed);
+                    InputStream input = autoDetect ? 
factory.createCompressorInputStream(source)
+                            : 
factory.createCompressorInputStream(CompressorStreamFactory.PACK200, source)) {
+                assertArrayEquals(expected, IOUtils.toByteArray(input));
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { false, true })
+    void testLimitFailureClosesInput(final boolean failOnClose) throws 
IOException {
+        final AtomicBoolean closed = new AtomicBoolean();
+        final InputStream source = new 
ByteArrayInputStream(Files.readAllBytes(getFile("bla.pack").toPath())) {
+            @Override
+            public void close() throws IOException {
+                closed.set(true);
+                if (failOnClose) {
+                    throw new IOException("Test close failure");
+                }
+                super.close();
+            }
+        };
+        assertThrows(MemoryLimitException.class, () -> 
Pack200CompressorInputStream.builder().setInputStream(source).setMemoryLimitKiB(0).get());
+        assertTrue(closed.get());
+    }
+
+    @Test
+    void testResetLimitToUnlimited() throws IOException {
+        final Pack200CompressorInputStream.Builder builder = 
builder(Origin.FILE).setMemoryLimitKiB(0);
+        assertThrows(MemoryLimitException.class, builder::get);
+        try (InputStream input = builder.setMemoryLimitKiB(-1).get()) {
+            assertArrayEquals(unpackedBytes(), IOUtils.toByteArray(input));
+        }
+    }
+
+    @Test
+    void testTempFileIgnoresLimit() throws IOException {
+        try (InputStream input = 
builder(Origin.FILE).setStrategy(Pack200Strategy.TEMP_FILE).setMemoryLimitKiB(0).get())
 {
+            assertArrayEquals(unpackedBytes(), IOUtils.toByteArray(input));
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { -1, -2, Integer.MIN_VALUE, Integer.MAX_VALUE })
+    void testUnrestrictiveLimits(final int limit) throws IOException {
+        try (InputStream input = 
builder(Origin.FILE).setMemoryLimitKiB(limit).get()) {
+            assertArrayEquals(unpackedBytes(), IOUtils.toByteArray(input));
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(Origin.class)
+    void testZeroLimit(final Origin origin) {
+        final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> 
builder(origin).setMemoryLimitKiB(0).get());
+        assertEquals(0, exception.getMemoryLimitInKb());
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/harmony/unpack200/Codec_decodeInts_OutOfMemoryErrorTest.java
 
b/src/test/java/org/apache/commons/compress/harmony/unpack200/Codec_decodeInts_OutOfMemoryErrorTest.java
index cdab7e663..44526f13b 100644
--- 
a/src/test/java/org/apache/commons/compress/harmony/unpack200/Codec_decodeInts_OutOfMemoryErrorTest.java
+++ 
b/src/test/java/org/apache/commons/compress/harmony/unpack200/Codec_decodeInts_OutOfMemoryErrorTest.java
@@ -78,7 +78,7 @@ class Codec_decodeInts_OutOfMemoryErrorTest {
     @Test
     void test() throws IOException {
         final byte[] input = Base64.getDecoder().decode(BASE64_BYTES);
-        try (InputStream is = new Pack200CompressorInputStream(new 
ByteArrayInputStream(input), Pack200Strategy.TEMP_FILE)) {
+        try (InputStream is = 
Pack200CompressorInputStream.builder().setInputStream(new 
ByteArrayInputStream(input)).setStrategy(Pack200Strategy.TEMP_FILE).get()) {
             // do nothing
         }
 

Reply via email to