Close nested threads

Possible duplicate:
Best way to close nested threads in Java?

How do we close nested threads? Closing everyone? If so, what order?

FileOutputStream out = new FileOutputStream("data.txt", true); PrintWriter pout = new PrintWriter(out); /* do some I/O */ pout.close(); out.close(); 

or closing the stream itself will be closed.

 pout.close(); // Is this enough? 
+4
source share
2 answers

When closing threads with a chain, you only need to close the external thread. Any errors will propagate along the chain and be caught.

Take a look here . This question was probably asked earlier.

+8
source

Always close resources with the finally block:

 acquire(); try { use(); } finally { release(); } 

Your only resource here is FileOutputStream , so it is the only one that really needs to be closed. If the PrintWriter constructor was supposed to be thrown, you really should free the FileOutputStream anyway, which excludes just closing the PrintWriter .

Notice you really want flush PrintWriter . This should only be done in a case other than exception, and therefore ultimately not required.

+3
source

All Articles