Search code examples
javatomcatnio

Why Tomcat's Non-Blocking Connector is using a blocking socket?


I was reading about Non-blocking I/O, java NIO and tomcat connectors, looked at the code of tomcat's NIO Connector, and found this in NioEndpoint.bind():

serverSock.configureBlocking(true); //mimic APR behavior

I don't have experience with NIO, so can someone explain how it is non-blocking when the socket is configured to be blocking?


Solution

  • Looks like the following line was introduced at this commit https://github.com/apache/tomcat/blob/bd8122700c2e70e5adbaddcd289fb1a974f981fe/java/org/apache/tomcat/util/net/NioEndpoint.java

    As far as I can tell this is NioEndpoint is using blocking ServerSocketChannel in order for it to block and wait for an incoming connection and only after it accepts it it processes this incoming socket channel in a non-blocking manner (see setSocketOptions method).

    The alternative to make ServerSocketChannel a non-blocking one will result as author points out into a busy read - that is a thread will be constantly polling for incoming connections as accept() in non-blocking mode may return null.

    You can find some useful explanation here.

    P.S. I presume that cryptic APR stands for Apache Portable Runtime.