Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will not closing a stringwriter cause a leak?

I realize that in java the GC will eventually cleanup objects, but I'm asking if it is bad practice to not close your string writer, currently I am doing this:

 private static String processTemplate(final Template template, final Map root) {         StringWriter writer = new StringWriter();         try {             template.process(root, writer);         } catch (TemplateException e) {             logger.error(e.getMessage());         } catch (IOException e) {             logger.error(e.getMessage());         }         finally {          }          return writer.toString();     } 

Should I be closing the writer and creating a new String like this:

String result = "";  ...  finally {   result = writer.toString();   writer.close(); } 

Is this better to do?

like image 820
Blankman Avatar asked Jan 26 '13 23:01

Blankman


2 Answers

The javadoc is quite explicit:

Closing a StringWriter has no effect.

And a quick look at the code confirms it:

public void close() throws IOException { } 
like image 55
assylias Avatar answered Sep 23 '22 07:09

assylias


It's not holding any non-memory resource. It will be garbage collected like anything else. The close() probabaly merely exists because other writer objects do hold resources that need to be cleaned up, and the close() is needed to satify the interface.

like image 25
James Curran Avatar answered Sep 23 '22 07:09

James Curran