Reputation: 669
I have a method (getRequest) which opens URLConnection and returns InputStream, here i am not closing the URLConnection.
In the sendHTTPMessage i am closing the InputStream and ObjectInputStream.
So will it create problem as i have not closed the URLConnection, as per my understanding it open a socket connection with the server ?
public InputStream getRequest(String url) throws IOException {
URL url = new URL(url);
URLConnection con = url.openConnection();
con.setUseCaches(false);
this.sendHeaders(con);
return con.getInputStream();
}
private Object sendHTTPMessage(HashMap<String, Object> params) {
Object resultobj = null;
InputStream in = null;
ObjectInputStream ois = null;
try {
in = sendGetMessage(params);
if (in != null) {
ois = new ObjectInputStream(in);
serviceResult = (Object)ois.readObject();
}
} catch (Exception var14) {
logger.error("Error during closing :", var14);
} finally {
try {
if (in != null) {
in.close();
}
if (ois != null) {
ois.close();
}
} catch (IOException var13) {
logger.error("Error during closing :", var13);
}
}
return resultobj;
}
Upvotes: 2
Views: 3802
Reputation: 136102
If you dont close InputStream your connection will stay opened for indefinite time which will hold open resources both on client and server side. Try this test:
URL url = new URL("https://www.google.com/");
List l = new ArrayList();
for(int i = 0; i< 100000; i++) {
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
in.close();
l.add(con);
System.out.println(i);
}
Run it and after some time check open connection on your machine with netstat command. Then stop, remove in.close(), run test again and check netstat. You will see that in the second test connections stay open and their number grows
Upvotes: 2