【问题标题】:Not Closing URLConnection不关闭 URLConnection
【发布时间】:2018-10-24 07:05:28
【问题描述】:

我有一个方法 (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;
    }

【问题讨论】:

    标签: java spring http connection urlconnection


    【解决方案1】:

    如果您不关闭 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(),再次运行测试并检查 netstat。你会看到在第二个测试中连接保持打开并且它们的数量在增长

    【讨论】:

    • 我的问题是,如果我们不关闭 URLConnection 但您正在关闭 Inputstream,那么在这种情况下,连接仍将保持打开状态,或者在关闭 Inputstream 时 URLConnection 将自动关闭?
    • 我的意思是你应该先用 in.close 试试这个测试,然后不用,看看连接不会自动关闭。
    • java.net.URL 使用 InputStream.close 它实际上什么都不做,正如它在其文档中所说的那样。
    猜你喜欢
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2021-04-27
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多