Raman
Raman

Reputation: 885

JBoss input/output streaming

I'm have a deal with Spring MVC based application deployed under JBoss-4.2.3.GA and want to clarify how servlet input/output streaming works with huge requests/responses body. I'm bother about it because don't want to keep whole request/response in memory until call will be completely finished.

How can I detect exactly input/output stream implementation that JBoss passes to servlet? Or possible I can investigate its behavior in some kind of specification?

Thanks for any useful info about it.

Upvotes: 1

Views: 1183

Answers (1)

BalusC
BalusC

Reputation: 1109292

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.

Upvotes: 1

Related Questions