使用HttpURLConnection时遇到的资源未释放的问题

http://blog.sina.com.cn/s/blog_56beadc60100j9zu.html



今天自己写了一个压力测试的小程序,同时启100个线程,每个线程都串行地访问应用服务器上的一个jsp页面200次。在程序运行了一会儿以后,问题来了:

java.net.SocketException: No buffer space available (maximum connections reached?): connect
 at java.net.PlainSocketImpl.socketConnect(Native Method)
 at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
 at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
 at java.net.Socket.connect(Socket.java:516)
 at java.net.Socket.connect(Socket.java:466)
 at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
 at sun.net.www.http.HttpClient.openServer(HttpClient.java:365)
 at sun.net.www.http.HttpClient.openServer(HttpClient.java:477)
 at sun.net.www.http.HttpClient.(HttpClient.java:214)
 at sun.net.www.http.HttpClient.New(HttpClient.java:287)
 at sun.net.www.http.HttpClient.New(HttpClient.java:299)
 at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:796)
 at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:748)
 at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:673)
 at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:840)

到网上查了查,应该是资源耗尽了,但是没有找到解决的方法。
程序片断代码如下:
for (int j = 0; j < 200; j++) {
    long beginTime = System.currentTimeMillis();
    URL url = new URL("...");
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");
    OutputStream os = httpURLConnection.getOutputStream();
    
    keywordNum = random.nextInt(myKeywords.length);
    
    os.write(("keyword=" + myKeywords[keywordNum]).getBytes("UTF8"));
    os.flush();
    os.close();
    int i = 0;
    int contentLength = 0;
    contentLength = httpURLConnection.getContentLength();
    long endTime = System.currentTimeMillis();
    System.out.println("Thread '" + name + "' search keyword '" + myKeywords[keywordNum] + "' and get content in " + (endTime - beginTime) + " Millis, length=" + contentLength);
   }

后来想了想,既然资源没释放,释放就可以了。查了一下HttpURLConnection有个disconnect方法,但是加上后也没有用。再找,jdk的docs里说,HttpURLConnection这个对象关掉相关的InputStream和OutputStream可以释放掉相关资源,于是试了下,在contentLength = httpURLConnection.getContentLength();这行后面又加了2行:
    InputStream is = httpURLConnection.getInputStream();
    is.close();

问题解决了。
原来只是知道如果不调用httpURLConnection的getContentLength或其它get方法,请求是不会提交的,一般如果不需要也不会去调getInputStream,没想到还有个释放资源的问题。

你可能感兴趣的:(使用HttpURLConnection时遇到的资源未释放的问题)