Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FILEUPLOAD-337 - Reuse the byte array buffer #91

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/main/java/org/apache/commons/fileupload2/util/Streams.java
Expand Up @@ -20,6 +20,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;

import org.apache.commons.fileupload2.InvalidFileNameException;

Expand All @@ -41,6 +42,11 @@ private Streams() {
* {@link #copy(InputStream, OutputStream, boolean)}.
*/
public static final int DEFAULT_BUFFER_SIZE = 8192;
/**
* The {@link ThreadLocal} where the buffer will be store temporary to reuse.
* @since 2.0
*/
private static final ThreadLocal<SoftReference<byte[]>> BUFFER_REF = new ThreadLocal<>();

/**
* Copies the contents of the given {@link InputStream}
Expand All @@ -65,7 +71,7 @@ private Streams() {
public static long copy(final InputStream inputStream, final OutputStream outputStream,
final boolean closeOutputStream)
throws IOException {
return copy(inputStream, outputStream, closeOutputStream, new byte[DEFAULT_BUFFER_SIZE]);
return copy(inputStream, outputStream, closeOutputStream, getIOBuffer());
}

/**
Expand Down Expand Up @@ -182,5 +188,23 @@ public static String checkFileName(final String fileName) {
}
return fileName;
}
/**
* <P>Gets the new instance of an {@code array}. If the {@code array} has been previously created,
* the same instance is returned.</P>
* @see #copy(InputStream, OutputStream, boolean, byte[])
* @return the temporary buffer, which is to be used for copying data.
*/
protected static byte[] getIOBuffer() {
byte[] buffer = null;
final SoftReference<byte[]> ref = BUFFER_REF.get ();
if (ref != null) {
buffer = ref.get();
}
if (buffer == null) {
buffer = new byte[DEFAULT_BUFFER_SIZE];
BUFFER_REF.set (new SoftReference<>(buffer));
}
return buffer;
}

}