开发者

how to response.setHeader works?

I have a filter in java that detect if the generation time is more than 200 then, it set cache-control header to a certain time.

This is made to avoid a server slow down, sort of autobalancing its load.

I have a doubt about it:

Is, by any chance, the serlvet containter using more memory, when it write the body before writing some of the response headers ?

Can the servlet container (tomcat or other) write the data to the connection while I do resp.write() ?

I am concern about memory issue. I think it may use extra memory to generate all开发者_开发知识库 the response, without buffer any, until the response is done, and then the servlet container starts to write.


It depends on your application container, and this will absolutely 100% not have a significant impact on memory usages. If buffer size in writing responses is any issue, Java probably isn't the platform for you.

Up the hardware abandon the platform. If you have memory-usage issues, you're probably looking in the wrong place.


MISUNDERSTANDING: I thought there was a thread waiting 200 millis, and then writing the header when notbing happened yet. NOT the case (header to be written at end of response generation). The issues below would hold in such a case, but I'll try again to answer what you really wanted.


I don't believe "response" in servlets is meant to be thread-safe -- you should not try to write data into the response variable in a supplemental thread (if I am understanding the "wait 200 milliseconds" logic) while the primary request handler thread is servicing the request.

In addition to the problem noted about part of the response being flushed before before your filter writes its "header", data may simply be lost or garbled beyond recognition (not just out of sequence).

HOWEVER, you could make your filter provide a wrapper for the response. Make the wrapper class threadsafe, and make it buffer the output. Then, you could check (in a synchronized, atomic fashion) after 200 millis to see if there is anything in the response buffer, and flag headers as appropriate if not.


Rather than configuring the buffer size to what you hope is "infinity", you may be better off creating a dynamic proxy / invocation handler pair as a wrapper around the response implementation.

See http://www.javaworld.com/javaworld/jw-11-2000/jw-1110-proxy.html

Your filter creates the invocation handler and puts it in the dynamic proxy, which you pass into subsequent filters / servlet in the chain in place of the real response implementation.

When the stuff deeper in the chain returns, you generate the header if needed, and get the buffered data out of your proxy, so that you can write the body after the header(s).

Yes, it uses memory. Can't say I would worry about that too much. If your application returns a 20 MB "page", you might want to address that as a problem in and of itself. (pagination, etc)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜