Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can disconnect() be safely called from another thread to cancel an ongoing HttpURLConnection?

Tags:

java

android

If I have a java.net.HttpURLConnection that's receiving data (or is about to receive data) in a worker thread, is it safe to call disconnect() to stop it at any point of the connection's lifecycle in another thread?

I'm wondering about this because I couldn't find a clearly documented way to abort an ongoing HTTP connection. Interrupting the worker thread by calling Thread.interrupt() won't work because the InputStream you get from HttpURLConnection is not interruptible.

I did some experiments that look like this:

// MyRequest.run() gets an HttpURLConnection by calling someUrl.openConnection()
MyRequest request = new MyRequest(someUrl);

FutureTask<SomeResult> task = new FutureTask<SomeResult>(request);
someExecutor.execute(task);

// The connection opens, data comes in, ...

// Get the HttpURLConnection from the request, call disconnect()
// Should be part of the cancel() of a FutureTask subclass
request.getConnection().disconnect();    

It seems to work, and both the connection and the socket object it creates will be eventually cleaned up by gc. Still, I wonder if that's the right way to do it? Will there be any issue with calling disconnect() from another thread?

like image 784
lukhnos Avatar asked Nov 13 '22 07:11

lukhnos


1 Answers

That will work, if you handle it correctly in the task. The better way to do that is to check the interruptState of the task while you read from the InputStream.

For example with BufferedReader:

HttpURLConnection conn = null;
try {

      //open Connection

   BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
   for(String line = br.readLine(); line != null && !Thread.currentThread().isInterrupted(); line = br.readLine()) {
         //do something
   }
} catch(IOException io) {
     //error handling
} finally {
   if(conn != null)
          conn.disconnect();
}
like image 58
NerdNeo Avatar answered Nov 14 '22 21:11

NerdNeo