*
The moose likes Servlets and the fly likes Must close PrintWriter in servlet when done? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Must close PrintWriter in servlet when done?" Watch "Must close PrintWriter in servlet when done?" New topic
Author

Must close PrintWriter in servlet when done?

Bill Pearce
Ranch Hand

Joined: Sep 19, 2000
Posts: 53
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

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Jan 07, 1999
Posts: 6920
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.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Frank Lin
Ranch Hand

Joined: Jan 26, 2001
Posts: 76
It should be closed after flush() so the PrintWriter object is elligible for garbage collection immediately.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Must close PrintWriter in servlet when done?
 
Similar Threads
JSP VS. SERVLETS
Do i need to close PrintWriter
Request Dispatcher doubt
Ocurrio un error:java.io.IOException: Stream closed
Servlet chaining