4

I have the block code as follow:

URL url = new URL("http://abc.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream());

StringBuilder sb = new StringBuilder();

String str = null;

while (null != (str = reader.readLine())) {
    sb = sb.append(str);
}

resStr = sb.toString();

reader.close();
con.disconnect();

There are two input steams that I don't close in the block code above.

First is new InputStreamReader() and the second is con.getInputStream(). I have new two input but I don't close them. For that reason, it can be memory leaks?

Note: I'm using jdk1.7.0_21

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Thinh Phan
  • 655
  • 1
  • 14
  • 27
  • 10
    Since you already closed `reader`, the wrapped stream will automatically get closed. – Rohit Jain Jul 05 '13 at 08:32
  • Thanks @DanielRenshaw. I clearly understand this matter. – Thinh Phan Jul 05 '13 at 08:38
  • 1
    Since you are using Java 7, you should make use of the [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) construct to ensure your `reader` object is closed. Currently, `reader` will not be closed if an exception occurs. I.e. `try (BufferedReader reader = new Buff...) { // reading code }` – Duncan Jones Jul 05 '13 at 08:51

1 Answers1

3

To sum up the comments: You have no memory leak because closing the reader will also close the underlying stream.

As you use Java 7 you can use the magic of try-with-resource

URL url = new URL("http://abc.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));)
{
    StringBuilder sb = new StringBuilder();

    String str = null;

    while (null != (str = reader.readLine()))
        sb = sb.append(str);

    resStr = sb.toString();
}

con.disconnect();
mkdev
  • 972
  • 9
  • 12