Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a URL connection upon thread interruption Java

I have a multithreaded program that visits URLs. The threads are run through an executor service, and when the user chooses to quit through the GUI, the program attempts to interrupt the threads by calling executor.shutdownNow(). However, it takes a very long time for the program to shut down because many of the threads are blocked in a url.openStream() call, and since this does not throw InterruptedException, so far I've been forced to just check before and after the call for Thread.currentThread().isInterrupted().

I'm wondering if there is a better way to interrupt a URL connection upon thread interruption? Otherwise, what would be the best approach to let the program shutdown as quickly as possible?

Note that I would prefer not to set a timeout on the connections because I would like all URLs to be visited while the program is still running.

like image 861
b_pcakes Avatar asked Nov 21 '15 21:11

b_pcakes


1 Answers

If you look at the Javadocs for URLConnection, it gives you a hint on this: If you call getInputStream or getOutputStream on the URLConnection and then close either of these streams, it will close the connection. If you are stuck waiting on getInput/OutputStream call, then I don't think anything can be done. But if you have the stream, close it (it'll throw an IOException and release any threads waiting on the stream) and the connection is finished

FYI: I have found that this method of closing an InputStream either when you want it to time out or when you just want to stop processing is highly effective, much more so than using interrupt()

like image 74
ControlAltDel Avatar answered Oct 21 '22 22:10

ControlAltDel