How to stop url connection when interrupting java thread

I have a multi-threaded program that visits URLs. Streams are launched through the executing service, and when the user decides to exit the GUI, the program tries to interrupt the streams by calling it executor.shutdownNow(). However, it takes a very long time to complete the program, because many threads are blocked during the call url.openStream(), and since it does not quit InterruptedException, so far I had to simply check before and after the call Thread.currentThread().isInterrupted().

I am wondering if there is a better way to disconnect from the url when the stream is interrupted? Otherwise, what would be the best approach to shutting down the program as quickly as possible?

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

+4
source share
3 answers

If you look at Javadocs for URLConnection , it will give you a hint: if you call getInputStream or getOutputStream on URLConnection and then close any of these streams, it will close the connection. If you are stuck waiting for a call to getInput / OutputStream, then I do not think that something can be done. But if you have a thread, close it (it will throw an IOException and release any threads waiting in the thread), and the connection is completed

FYI: , InputStream , - , , , ()

+1

Apache HttpClient

Apache HttpClient URLConnection. , URLConnection, , . , Java , , . , .

URLConnection

HTTP HTTPS URL- , URLConnection HttpURLConnection HttpsURLConnection . , . URLConnection (. ). -, HttpURLConnection. , HTTP HTTPS URL-.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

HttpURLConnection disconnect(), . , getInputStream() , read() , SocketException: Socket closed:

conn.disconnect();

Caveat:
Javadoc disconnect():

disconnect() , .

, JDK1.8 Ubuntu Android, , , , , true, URLConnection. , , , " ".

0

The easy answer is to use System.exit(0), which will cause all threads to die.

-2
source

Source: https://habr.com/ru/post/1616884/


All Articles