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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With