tags:

views:

315

answers:

4

I've got some production code that does something like:

HttpServletRequest httpServletRequest
...
DataInputStream dis = new DataInputStream(httpServletRequest.getInputStream())

These streams are never closed explicitly. I'm assuming here that the servlet container manages this (JBOss Web). What is the correct way to handle this?

+1  A: 

The container will handle this. It is always good coding style to close resource in the same place you allocated it. (I was wrong on that in my original post. I thought you opened the stream. Should read more carefully.)

Thomas Jung
+4  A: 

The thumb rule in I/O is, if you did not open/create the inputstream source yourself, then you do not necessarily need to close it as well. Here you are just wrapping the request's inputstream, so you don't necessarily need to close it.

If you did open the input yourself by e.g. new FileInputStream("c:/file.ext") then you obviously need to close it yourself in the finally block. The container ought to do so under the hood.

BalusC
+3  A: 

You should absolutely not close these streams yourself, that is the container's job. Doing so manually risks interfering with the request lifecycle, and some containers may object violently to you doing this.

skaffman
A: 

The specification (up to the 3.0 candidate) does not say (as far as I can tell). In the absence of canonical information, you might be at the mercy of the implementation.

The source code for the reference implementation is mentioned on the Sun Servlet page:

The reference implementation is included in the Java EE 5 SDK and also in the open-source Java Platform, Enterprise Edition (Java EE) application server, available through the GlassFish project, on java.net. The reference implementation source code for Servlet technology is available from the svn repository on java.net. Additional information on all webtier technologies in GlassFish can be found at the GlassFish Webtier page.

Checking the behaviour may be as close to a definitive answer as you'll get.

McDowell