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)
...
You probably have to close the stream. Per Java bug #4514257, calling Thread.interrupt() on any InputStream.read() fails.
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.