According to the API, URL.openStream() is shorthand for URL.openConnection().getInputStream(). Is the connection closed when the input stream is closed, or does it wait until the URL (and connection, stream, etc) is garbage collected?
If you are opening an HTTP type of URL like http://java.sun.com, then the method will return an HttpURLConnection object, which will then have it's connect method called when the getInputStream happens.
Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.
So the answer is - depends on your particular TCP/IP stack implementation. From experience, the Microsoft stack leaves connections in a 'time wait' state for a long time - yuck.
Treat it like garbage collection - close the stream when you are done with it and then let the JVM and underlying system worry about the network resources. [ November 02, 2005: Message edited by: Kelly Loyd ]
Joined: Dec 13, 2004
Thank you for the reply Kelly!
Hmm, so if I have an RSS reader that loops through a list of URL addresses, creates a URL object for each one, and opens and closes it's InputStream, it is possible that the hundreds of connections are kept open after the stream is closed? Or does this not count as a "persistent" connection? Or does it depend on the OS (Unix in my case)?
Thank you, Yuriy
Joined: Oct 10, 2005
My guess is that calling the close() should release any resources associated with the InputStream, but leave the connection open, only if the connection is persistent (and probably shared).
I think what the API is saying is that the Java Virtual Machine won't guarantee what happens to the connection underneath all of this.
If you do a netstat -an | grep :80 , you will see exactly what is happening with the connections.
Your mileage may vary!
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com