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?
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.
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.)
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With