How internal InputStreams URLConnection are closed

I am implementing my own protocol handler and just stepped through this code into the JDK.

 public Object getContent() throws IOException {
     // Must call getInputStream before GetHeaderField gets called
     // so that FileNotFoundException has a chance to be thrown up
     // from here without being caught.
     getInputStream();
     return getContentHandler().getContent(this);
 }

      

See URLConnection

I thought I InputStream

should be closed. Since the return value of the method is getInputStream()

not stored, it cannot be retrieved and therefore not closed.

I thought it might cause file descriptors to be opened in the case of the protocol file://

and wrote this test program.

File tempFile = File.createTempFile("test", "test");
URL url = tempFile.toURI().toURL();
URLConnection openConnection = url.openConnection();

// getContent() should create 2 InputStreams
InputStream content = (InputStream) openConnection.getContent();
content.close(); // only one is closed

boolean deleted = tempFile.delete();
System.out.println("Temp file deleted " + deleted);

      

But the result

Temp file deleted true

      

If I comment content.close()

I get

Temp file deleted false

      

Now I'm just confused as to how should I implement my own URLConnection

.

  • Should I finalize on mine InputStream

    and close them
  • Should I use WeakReference

    for threads to automatically close

Both options seem like a workaround.

Did I miss something?

EDIT

I also thought that every call getInputStream

should return the same instance because it is unnamed openInputStream

or whatever.

This explains why it FileURLConnection

works in my example. But it seems strange that the method getContent

assumes that it ContentHandler

will access the same InputStream

, and thus the stream will be closed after reading the content.

Of course, it seems obvious that I have to read the content to create the content object, but if I just go back to the lazy content object, the stream won't be closed.

Also the ContentHandler

javadoc doesn't say it ContentHandler

should closeInputStream

Given the URL connection stream located at the beginning of the object view, this method reads this stream and creates an object from it.

+3


source to share





All Articles