Is there a memory leak if InputStream is not closing?

I have a block code as follows:

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 pairs that I do not close in the block code above.

First, new InputStreamReader() , and the second is con.getInputStream() . I have two new inputs, but I do not close them. For this reason, could it be a memory leak?

Note. I am using jdk1.7.0_21

+4
source share
1 answer

To summarize the comments: You do not have a memory leak, since closing the reader will also close the underlying thread.

How do you use Java 7, you can use try-with-resource magic

 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(); 
+3
source

Source: https://habr.com/ru/post/1489857/


All Articles