Fre*_*ind 6 java sockets blocking
在由线程池运行的任务中,我想将一堆字符串写入远程,并且有一个标志来指示任务是否已被取消.
我正在使用以下代码以确保我可以尽快停止:
public void sendToRemote(Iterator<String> data, OutputStream remote) {
try {
System.out.println("##### staring sending")
while(!this.cancelled && data.hasNext()) {
remote.write(data.next())
}
System.out.println("##### finished sending")
System.out.println("")
} catch(Throwable e) {
e.printStackTrace();
} finally {
remote.close();
}
}
Run Code Online (Sandbox Code Playgroud)
我有时发现,如果我给这个方法提供一个非常大的数据(或无限的迭代器),即使我将其设置this.cancelled为true以后,它也无法及时完成.代码似乎被阻止,经过很长一段时间(大约1分钟)后,会出现如下错误:
java.net.SocketTimeoutException: write blocked too long
Run Code Online (Sandbox Code Playgroud)
所以我想remote.write如果有太多的数据要发送,方法可能会阻塞自己,但是遥控器不会及时消耗它.虽然我设置this.cancelled了true,但是该方法已经remote.write(data.next())在行中被阻塞了很长时间,所以它没有机会检查值this.cancelled并跳过循环.相反,最后,它会SocketTimeoutException在很长一段时间后抛出.
我的理解是否正确?如果是,如果有太多数据要发送,我怎么能避免阻塞?
| 归档时间: |
|
| 查看次数: |
1079 次 |
| 最近记录: |