While executing the following under Java 7, the program hangs. However, it doesn’t hang under Java 6.
package pkg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
final public class Main
{
public static void main(String[] args)
{
try
{
URL url = new URL("http://en.wikipedia.org/wiki/Cancer");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while((line = in.readLine())!= null)
{
System.out.println(line);
}
in.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
What might be the reason?
The code is not guaranteed to work under any version of Java. YOu might have gotten luck with a particular Java runtime. The issue is that you’re trying to buffer input coming from the network, and this can hang. You must set the buffer size to 1 (effectively turning off buffering) before using
BufferedReaderwith a network connection or withSystem.in; otherwiseread()calls can hang trying to buffer input that’s not available, and may never become available. See the (new) second argument to theBufferedReaderconstructor: