Java: how to quickly stop HttpURLConnection.getInputStream?
This is in a simple test program. The main thread runs multiple child threads. I added: . Runtime.getRuntime () addShutdownHook (hookThread);
When the ^ C button is pressed on the JVM process, this hookThread will set the global termination flag and call interrupt () on all child threads.
I want all child streams to return then, but interrupt () does nothing for the child stream if it is in HttpURLConnection.getInputStream (). The child thread returns after a timeout (30 seconds) which is too much for me.
What's the best way to promptly interrupt the HttpURLConnection.getInputStream () call?
After the top of the child thread's stack, after calling interrupt ():
"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)
...
source to share
You cannot interrupt this call.
You can set a shorter timeout before making the call, or find an HTTP client library that supports intermittent I / O through the NIO package.
Also, you should only interrupt the threads that you have. If you have created each thread in the process and understand how they react to interrupts, this is fine, but otherwise it is dangerous to blindly interrupt threads.
source to share