Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a servlets PrintWriter out stream really need to be closed?

I wrote a simple servlet as follows:

public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        // [do stuff with the PrintWriter]
        out.close();
    }
}

Is it necessary to close the PrintWriter out stream? If I don't close the stream will that affect anything further?

like image 814
ajduke Avatar asked Oct 18 '11 08:10

ajduke


People also ask

Do you need to close a PrintWriter?

It should be closed after flush() so the PrintWriter object is elligible for garbage collection immediately.

Do I need to close ServletOutputStream?

You indeed don't need to do so. Thumb rule: if you didn't create/open it yourself using new SomeOutputStream() , then you don't need to close it yourself. If it was for example a new FileOutputStream("c:/foo. txt") , then you obviously need to close it yourself.

What is the method used as an alternate for the Close method which automatically writes unto a file?

When you call close() the Buffer flushes into the file. You can also call flush() for forcing the data to be written without closing the stream.


1 Answers

If it's not you that's opening the stream, you should not close it.

The stream is opened by the container so the responsibility for closing lies with it.

like image 176
Bozho Avatar answered Oct 21 '22 06:10

Bozho