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?