Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Must close PrintWriter in servlet when done?

 
Bill Pearce
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
If I open a PrintWriter in a servlet by calling res.getWriter() and output all my HTML back to the client, should I explicitly close it by calling out.close()? I thought yes (I even put it in a finally block), but another developer says no. Which is correct?
Thanks,
Bill
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no need for explixitly closing the PrintWriter object as once all the response has been send,the Http connection closes and the stram gets closed.But it's a good coding practice to close all the resources you have opened in the program before you exit
bye
sam
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To some degree this depends on the servlet container. It's usually safe to leave the stream open, as the container has to account for that and try to flush and close it. Almost all "real" servlet containers also work quite happily of you do close the stream, but some just wrap the socket stream and closing that would potentially cause it to fail to flush your final output.
As a general rule, for ultimate portability it's probably best to flush but not close the stream. If you are using one of the well-known containers it shouldn't matter.
 
Frank Lin
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It should be closed after flush() so the PrintWriter object is elligible for garbage collection immediately.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic