我有一个方法(getRequest),它打开URLConnection并返回InputStream,这里我不关闭URLConnection。
在sendHTTPMessage中,我将关闭InputStream和ObjectInputStream。
因此,它会不会造成问题,因为我还没有关闭URLConnection,根据我的理解,它会打开与服务器的套接字连接吗?
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;
}发布于 2018-10-24 08:00:37
如果您不关闭InputStream,您的连接将在不确定的时间内保持打开,这将在客户端和服务器端保存开放的资源。试试这个测试:
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);
}运行它,一段时间后,使用netstat命令检查机器上的打开连接。然后停止,删除in.close(),再次运行test并检查netstat。在第二个测试中,您将看到连接保持打开状态,并且它们的数量不断增加。
https://stackoverflow.com/questions/52962826
复制相似问题