Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel file download from another thread at any time

Tags:

java

I'm using HttpURLConnection to download a file. Can I cancel the download from another thread? If not, what method for file download should I use?

like image 840
fhucho Avatar asked Dec 14 '10 17:12

fhucho


2 Answers

My suggestion would be to use HttpClient instead of HttpUrlConnection. It's a better library in many respects.

Then, you could use:

final SimpleHttpConnectionManager connectionManager = 
            new SimpleHttpConnectionManager();
final HttpClient client = new HttpClient(connectionManager);

// ... and when it's time to close the connection from another thread
connectionManager.shutdown();

If you need to close multiple connections across multiple threads, you can reuse one instance of HttpClient and close them all in one go in a similar fashion:

static MultiThreadedHttpConnectionManager connectionManager = 
            new MultiThreadedHttpConnectionManager();
// HttpClient instance that can be shared across threads and create multiple connections
static HttpClient client = new HttpClient(connectionManager);

// ... and when it's time to close connections
connectionManager.shutdown();
like image 175
Oleg Ryaboy Avatar answered Oct 14 '22 09:10

Oleg Ryaboy


You can use the InterruptedException in conjunction with Tasks/Executors. Your spawned thread should be able to catch InterruptedException by wrapping the try/catch around the HttpURLConnection method that's doing the download. Java Concurrency In Practice, chapters 6 and 7 are relevant. Particularly 7.2 "Stopping a thread-based service".

like image 39
Chris Kessel Avatar answered Oct 14 '22 10:10

Chris Kessel