The servlet API does by default not keep the entire request and response body in memory. It's effectively your own processing/parsing code which does that.
As to request bodies, when processing it, you should not hold the entire body in a byte[]
. Each byte of a byte[]
consumes, yes, one byte of Java's memory. You should try to (re)write your code as such that it never holds the entire body in memory. Process it for example line-by-line or buffer-by-buffer and/or stream it immediately to an OutputStream
.
E.g. when the body is character based:
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(someOutputStream, "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
processIfNecessary(line);
writer.writeln(line);
}
or when the body is byte based:
BufferedInputStream input = new BufferedInputStream(request.getInputStream());
BufferedOutputStream output = new BufferedOutputStream(someOutputStream);
byte[] buffer = new byte[1024]; // 1KB buffer.
for (int length; (length = input.read(buffer)) > 0;) {
processIfNecessary(buffer);
output.write(buffer, 0, length);
}
As to response bodies, it will be kept in the memory until the buffer size. Anything beyond the buffer size will be flushed. The default buffer size is usually 2KB. This is configureable at appserver level and by ServletResponse#setBufferSize()
. When you set the buffer size too high, it will gobble memory.