Is it possible to disable () safely call from another thread to cancel the current HttpURLConnection connection?

If I have java.net.HttpURLConnection that receives data (or is going to receive data) in a workflow, is it safe to call disconnect() to stop it at any point in the connection's life cycle in another thread?

I'm curious about this because I could not find a clearly documented way to end the current HTTP connection. Interrupting a workflow by calling Thread.interrupt() will not work because the InputStream that you get from the HttpURLConnection is not interrupted.

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(); 

This seems to work, and both the connection and the socket object it creates will be eventually cleared by gc. However, I wonder if this is the right thing to do? Will there be a problem with calling disconnect() from another thread?

+4
source share
2 answers

This will work if you do the job correctly. The best way to do this is to check interruptState tasks while reading from an 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(); } 
+1
source

The document for HttpURLConnection says: "Instances of this class are not thread safe." Because disconnect is an instance method, you cannot call it in the documentation while you call any other method associated with the object. Typically, the I / O stream code almost always calls the methods associated with the HttpURLConnection, since these methods are blocked while waiting for the network.

If you make simultaneous calls, for example, security breaches of streaming in general, you can expect it to work fine when you fail badly in front of your most important client. :-)

0
source

All Articles