1

I use following code to read data form http request. In general cases it works good, but some time "httpURLConnection.getResponseCode()" throws java.net.BindException: Address already in use: connect

     ............
     URL url = new URL( strUrl );
     httpURLConnection = (HttpURLConnection)url.openConnection();
     int responseCode = httpURLConnection.getResponseCode();
     char charData[] = new char[HTTP_READ_BLOCK_SIZE];
     isrData = new InputStreamReader( httpURLConnection.getInputStream(), strCharset );
     int iSize = isrData.read( charData, 0, HTTP_READ_BLOCK_SIZE );
     while( iSize > 0 ){
            sbData.append( charData, 0, iSize );
            iSize = isrData.read( charData, 0, HTTP_READ_BLOCK_SIZE );
     }
     .................





 finally{
            try{
                if( null != isrData ){
                    isrData.close();
                    isrData = null;
                }

                if( null != httpURLConnection ){
                    httpURLConnection.disconnect();
                    httpURLConnection = null;
                }

                strData = sbData.toString();
             }
            catch( Exception e2 ){
            }

The code running on Java 1.6, Tomcat 6. Thank you

Boris
  • 175
  • 1
  • 13

2 Answers2

2

Get rid of the disconnect() and close the Reader instead. You are running out of local ports, and using disconnect() disables HTTP connection pooling which is the solution to that.

user207421
  • 289,834
  • 37
  • 266
  • 440
  • Good point, unfortunately it's didn't help, I still sow the Exception in log files in same frequency. – Boris Nov 18 '10 at 13:15
  • Then you need the sleep. You are running out of outbound ports, i.e. using all of them up within the TIME_WAIT period. – user207421 Nov 19 '10 at 02:24
1

You need to close() the Reader after completely reading the stream. This will free up underlying resources (sockets, etc) for future reuse. Otherwise the system will run out of resources.

The basic Java IO idiom for your case is the following:

Reader reader = null;
try {
    reader = new InputStreamReader(connection.getInputStream(), charset);
    // ...
} finally {
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • Everything closed. This problem solved by add Thread.sleep(500), but I don't like this solution. – Boris Nov 17 '10 at 15:13
  • *Did* you already close resources? If you didn't and you actually fixed the code to do so, then you need to restart the machine in order to force the unclosed resources to be freed up. – BalusC Nov 17 '10 at 15:25