BufferedReader ready method

2019-07-03 00:07发布

问题:

I am observing a strange behaviour with the java.io.BufferedReader's ready method which returns false inside Tomcat while it returns true when the same servlet is run within Jetty.

BufferedReader bufferedReader = httpRequest.getReader();
System.out.println(bufferedReader.ready());
/** Perform some read operation */

Output:

true //Jetty
false //Tomcat

I understand that the BufferedReader#ready method only indicates if the next read is not going to blocked for the input(true) or not(false), but I am failing to understand the difference in its behavior between the two web server environments.

If someone has already come across this situation before ,I need help in understanding this better ?

Thanks in advance.

回答1:

ready() returns true if the reader can guarantee that the next read won't block. The fact that it returns false doesn't guarantee that the next read will block, and a Reader implementation is authorized to always return false from this method.

Jetty and Tomcat are two different implementations of a Java EE web container, and each provides its own HttpServletRequest implementation. They've thus obviously made different design choices, but each of them respects the specification.

You should simply not rely on this method. I've never met a case where using it was useful.