在读取网络中流数据时,通常要创建一个网络连接。然而在创建URL连接时,我们通常会忽略掉设置ConnectTimeout,以及ReadTimeout:
URL url = new URL(urlstr); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while(!in.ready()){ //等待 } while ((line = in.readLine()) != null) { //执行处理 } in.close(); conn.disconnect();
这种情况下,往往会造成URL阻塞,或者读取流的阻塞。所以应该注意设置超时:
URL url = new URL(urlstr); URLConnection conn = url.openConnection(); conn.setReadTimeout(AWAIT_TERMINATION_TIME_OUT);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while(!in.ready()){ //等待 } while ((line = in.readLine()) != null) { //执行处理 } in.close(); conn.disconnect();
同样在使用一些其他的网络读写相关的类对象时也应该注意设置超时,否则很有可能造成程序的阻塞挂起。所以也可以相应的设置超时:
for (Future<Object> future : list) { try { Object o = future.get(AWAIT_TERMINATION_TIME_OUT,TimeUnit.MILLISECONDS); //other processing } catch (InterruptedException e) { } catch (ExecutionException e) { } catch (TimeoutException e) { } }
使用URL创建网络连接、网络流的阻塞问题,布布扣,bubuko.com
原文:http://www.cnblogs.com/forzhongyou/p/3904978.html