Java: How to promptly stop HttpURLConnection.getInputStream?

Go To StackoverFlow.com

3

This is in a simple test program. The main thread starts a number of child threads. I have added to main: Runtime.getRuntime().addShutdownHook(hookThread);

When ^C is pressed on the JVM process, this hookThread will set a global shutdown flag, and call interrupt() to all the child threads.

I want all the child threads to return then, but interrupt() does nothing to a child thread if it's in HttpURLConnection.getInputStream(). The child thread returns after its timeout (30 seconds), which is too much delay for me.

What's the best way to promptly interrupt a HttpURLConnection.getInputStream() call?

Following the the top of the stack of child thread after interrupt() has been called on it:

"Thread-0" prio=10 tid=0x0000000040b0f800 nid=0x3eab runnable [0x000000004211b000]
   java.lang.Thread.State: RUNNABLE
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.read(SocketInputStream.java:129)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
        - locked <0x00000000fd99ac88> (a java.io.BufferedInputStream)
        at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
        at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)
        - locked <0x00000000fd997670> (a sun.net.www.protocol.http.HttpURLConnection)
...
2012-04-05 23:34
by May


1

You probably have to close the stream. Per Java bug #4514257, calling Thread.interrupt() on any InputStream.read() fails.

2012-04-05 23:52
by Ryan Nelson
You can't close a stream that doesn't exist yet; the thread is blocked in the call to get the stream. How can you close it if you don't have a reference to it - erickson 2012-04-06 01:46
Hmm, you're right. It's strange that HttpURLConnection.getInputStream() actually requires reading from the socket. Regardless, Java ignores interrupt calls during a read(), so your suggestion of using NIO may be best - Ryan Nelson 2012-04-06 15:23


1

You can't interrupt this call.

You can set a shorter time-out before making the call, or you might find an HTTP client library that supports interruptible I/O through the NIO package.

Also, you should only interrupt threads that you own. If you created every thread in the process and understand how they respond to interrupts, that's okay, but otherwise it's dangerous to blindly interrupt threads.

2012-04-06 01:49
by erickson
Ads