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

你可能感兴趣的:((l = buffer.readLine()) != null堵塞不释放问题)