File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Servlets
Bookmark "Must close PrintWriter in servlet when done?" Watch "Must close PrintWriter in servlet when done?" New topic

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?
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
Frank Carver

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 ~ 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:
subject: Must close PrintWriter in servlet when done?
It's not a secret anymore!