This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!
See this thread for details.
Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ServletContext getResourceAsStream closing stream?

 
Larry Sellers
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just curious if anyone could elaborate on why I never see the InputStream being closed when it is obtained from ServletContext getResourceAsStream.
It appears that getResourceAsStream actuall calls getResource which returns a URL and then calls openStream on the URL object. In the case of a file resource from a web app it appears that this URLConnection is actually an implementation of HttpURLConnection which says this about close:

Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection.

So it appears that calling close() isnt needed? Is this correct?

Again I see lots of basic examples like this that never close the InputStream:



Thanks!
 
Travis Hein
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree, the inout stream fetched from the get resource as stream should be closed.
It is likely the examples that don't show a close are being brief to demonstrate the principle, or have copied the code snippet from other soueces.

The open network resources (e.g. the socket here for this HttpUrlConnection) will be closed when the object is garbage collected, but in a real system where there could be many frequent requests, it is possible there could be a bunch of no longer in use sockets that are just waiting to be cleaned up, and depending on how busy the system is and how many available client sockets remain for future requests, it's possible to get occasional intermitent failures due to a URL connection not being able to acquire a client socket.

So close when finished then right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic