Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is necessary to close the input stream returned from HttpServletRequest?

Tags:

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?

like image 327
Conor Avatar asked Nov 27 '09 11:11

Conor


People also ask

What happens if you don't close Inputstream?

People say that you may face a memory leak of you don't close() it. So what kind of a memory leak is that? resource-leak is probably more of a concern here. Handling inputstream requires OS to use its resources and if you don't free it up once you use it, you will eventually run out of resources.

What is the difference between ServletRequest and HttpServletRequest?

The ServletRequest and HttpServletRequest classes hold all of the accessible information about the client and the server. HttpServletRequest is a subclass of ServletRequest, and is passed to each servlet handler method (such as doGet(..), doPut(..), etc.)

Which method of the HttpServletRequest object is used to get the value?

getParameter() method to get the value of a form parameter. getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames() − Call this method if you want a complete list of all parameters in the current request.


2 Answers

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.

like image 181
BalusC Avatar answered Oct 05 '22 19:10

BalusC


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.

like image 32
skaffman Avatar answered Oct 05 '22 20:10

skaffman