Search code examples
springtcpscheduled-tasksnioserversocket

Could a @Scheduled non-blocking ServerSocketChannel accept() miss incoming TCP messages?


During code review, a colleague suggested changing a blocking TCP server to use a non-blocking java.nio.ServerSocketChannel with a @Scheduled method that repeatedly checks for new messages via accept().

My question is simple: Whatever interval is chosen, is there a risk of missing messages? To take an extreme example, let's say the checking interval is hugely increased to 1 hour and 1000 messages are sent during that time. accept() would only receive 1 message - so would the other 999 be missed? And if so, would they fail silently or would the TCP clients not be able to send them?


Solution

  • During code review, a colleague suggested changing a blocking TCP server to use a non-blocking java.nio.ServerSocketChannel with a @Scheduled method that repeatedly checks for new messages via accept().

    Why? Incoming connections don't occur according to a schedule. What problem is that intended to solve?

    My question is simple: Whatever interval is chosen, is there a risk of missing messages?

    Yes.

    *To take an extreme example, let's say the checking interval is hugely increased to 1 hour and 1000 messages are sent during that time. accept() would only receive 1 message - so would the other 999 be missed?

    There's a backlog queue, so you won't miss 999, but you'll certainly miss quite a few. Exactly how many is indeterminate.

    And if so, would they fail silently or would the TCP clients not be able to send them?*

    The TCP clients would get connect errors: connection refusals or timeouts, depending on the server platform.

    Don't do this. It's completely and utterly pointless. It doesn't solve any problem and it creates many more.