(l = buffer.readLine()) != null堵塞不释放问题

网络请求数据过程中偶发遇到readline()一直不结束问题:

try (InputStream is = conn.getInputStream()) {
    BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
    String l = null;
    while ((l = buffer.readLine()) != null) bs.append(l);
finally{
    if (conn != null) conn.disconnect()
}

jps & jstack -l pid:

Jstack定位

定位之后发现只这行:while ((l = buffer.readLine()) != null) bs.append(l);
“readLine() has the same problem with line ends that DataInputStream's readLine() method has; that is, the potential to hang on alone carriage return that ends the stream . This problem is especially acute on networked connections, where readLine() should never be used.”
这个方法会在遇到"/r"、"/n"、"/r/n"前一直堵塞。
有解决方案是用CountDownLatch设定超时时间:

private CountDownLatch latch = new CountDownLatch(1);
class URLReader implements Runnable {
        public void run() {
            URL oracle = new URL("http://www.oracle.com/");
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) System.out.println(inputLine);
            in.close();
            latch.countDown();
        }
}
URLReader urlReader = new URLReader();
Thread listener = new Thread(urlReader);
listener.setDaemon(true);
listener.start();
latch.await(20000, TimeUnit.MILLISECONDS);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。