ricks88
ricks88

Reputation: 33

HttpUrlConnection Leaking Sockets with "Can't identify protocol" error message: even after closing input stream and disconnecting socket

My application is periodically throwing Too Many Open files: Socket Exception. Lsof command shows that there are many broken sockets with "Can't identify protocol" message. So, I think somehow socket/stream are not getting closed even though I am doing clean up in final block as suggested in

Seeing too many lsof can't identify protocol

Java app with URLConnection leads "Too many open files"

Here is my code:

    private static Map<String, List<String>>getResponseHeaders (URL url) throws IOException {
        InputStream urlStream = null
        URLConnection urlConnection = null

        try{
            urlConnection = (HttpURLConnection)url.openConnection()
            urlConnection.setAllowUserInteraction(false)
            urlConnection.setRequestProperty("User-Agent", "Agent-123")
            urlConnection.setConnectTimeout(10000)
            urlConnection.setReadTimeout(15000)
            urlStream = urlConnection.inputStream
            return urlConnection.getHeaderFields()
        }catch (IOException ex){
             log.info( "Could not open the connection for url "+url +" error msg "+ex.message)
             throw ex
        }finally {
           if(urlStream){
              urlStream.close()
           }
           if(urlConnection){
               urlConnection.disconnect()
           }
     }

Looking for some help here. Thanks!

Upvotes: 3

Views: 5575

Answers (2)

Dev
Dev

Reputation: 12206

I don't know if this is completely on target but it sounds similar.

There was a problem in the JRE that wasn't fixed until JRE7. I don't know if the fix got backported to 6 eventually, it was not last time I checked. The bug showed up if you passed a hostname to a Socket and it threw an UnknownHostException the socket would leak a file descriptor until the garbage collector collected the dead socket object. The work around is that you resolve the hostname manually and give the socket the IP address instead or upgrade the JRE.

I could not locate the original bug report in Oracle's bug database that has the exact fix version.

Upvotes: 2

DaveH
DaveH

Reputation: 7335

In your finally block, if urlStream.close() threw an IOException, you wouldn't call urlConnection.disconnect(). Have you investigated to see whether that might be happening?

Upvotes: 0

Related Questions