【发布时间】:2013-04-17 19:28:57
【问题描述】:
如果我有一个在工作线程中接收数据(或即将接收数据)的java.net.HttpURLConnection,那么在另一个线程中的连接生命周期的任何时候调用disconnect() 来停止它是否安全?
我对此感到疑惑,因为我找不到明确记录的方法来中止正在进行的 HTTP 连接。通过调用Thread.interrupt() 来中断工作线程将不起作用,因为您从HttpURLConnection 获得的InputStream 是不可中断的。
我做了一些看起来像这样的实验:
// 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();
它似乎工作了,它创建的连接和套接字对象最终都会被 gc 清理掉。不过,我想知道这是否是正确的做法?从另一个线程调用disconnect()会有什么问题吗?
【问题讨论】: