diff --git a/src/main/java/org/xerial/snappy/SnappyOutputStream.java b/src/main/java/org/xerial/snappy/SnappyOutputStream.java index d6cfda9..709c804 100755 --- a/src/main/java/org/xerial/snappy/SnappyOutputStream.java +++ b/src/main/java/org/xerial/snappy/SnappyOutputStream.java @@ -65,8 +65,9 @@ public class SnappyOutputStream extends OutputStream { private final BufferAllocator inputBufferAllocator; private final BufferAllocator outputBufferAllocator; - protected final byte[] inputBuffer; - protected final byte[] outputBuffer; + // The input and output buffer fields are set to null when closing this stream: + protected byte[] inputBuffer; + protected byte[] outputBuffer; private int inputCursor = 0; private int outputCursor = 0; private boolean closed; @@ -340,6 +341,8 @@ public class SnappyOutputStream extends OutputStream { closed = true; inputBufferAllocator.release(inputBuffer); outputBufferAllocator.release(outputBuffer); + inputBuffer = null; + outputBuffer = null; } } diff --git a/src/test/java/org/xerial/snappy/SnappyOutputStreamTest.java b/src/test/java/org/xerial/snappy/SnappyOutputStreamTest.java index ef5f8f4..0942eb0 100755 --- a/src/test/java/org/xerial/snappy/SnappyOutputStreamTest.java +++ b/src/test/java/org/xerial/snappy/SnappyOutputStreamTest.java @@ -30,10 +30,12 @@ import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.lang.ref.WeakReference; import org.junit.Test; import org.xerial.snappy.buffer.BufferAllocatorFactory; import org.xerial.snappy.buffer.CachedBufferAllocator; +import org.xerial.snappy.buffer.DefaultBufferAllocator; import org.xerial.util.FileResource; import org.xerial.util.log.Logger; @@ -225,6 +227,18 @@ public class SnappyOutputStreamTest } } + @Test + public void closingStreamShouldMakeBuffersEligibleForGarbageCollection() throws IOException { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + SnappyOutputStream os = new SnappyOutputStream(b, 4095, DefaultBufferAllocator.factory); + WeakReference inputBuffer = new WeakReference(os.inputBuffer); + WeakReference outputBuffer = new WeakReference(os.inputBuffer); + os.close(); + System.gc(); + assertNull(inputBuffer.get()); + assertNull(outputBuffer.get()); + } + @Test public void longArrayCompress() throws Exception { long[] l = new long[10];