Setting timeout on blocking I/O ops with ServerSocketChannel doesn't work as expected <p>I'm working on a small group conversation server in Java and I'm currently hacking network code, but it seems like I cannot set right timeout on blocking I/O ops: chances are I've been bitten by some Java weirdness (or, simply, I misinterpret javadoc).</p> <p>So, this is the pertinent code from <code>ConversationServer</code> class (with all security checks and logging stripped for simplicity):</p> <pre><code>class ConversationServer { // ... public int setup() throws IOException { ServerSocketChannel server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(port), Settings.MAX_NUMBER_OF_PLAYERS + 1); server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS); int numberOfPlayers; for (numberOfPlayers = 0; numberOfPlayers &lt; Settings.MAX_NUMBER_OF_PLAYERS; ++numberOfPlayers) { SocketChannel clientSocket; try { clientSocket = server.accept(); } catch (SocketTimeoutException timeout) { break; } clients.add(messageStreamFactory.create(clientSocket)); } return numberOfPlayers; } // ... } </code></pre> <p>The expected behaviour is to let connect <code>Settings.MAX_NUMBER_OF_PLAYERS</code> clients at most, or terminate setup anyway after <code>Settings.AWAIT_PLAYER_MS</code> milliseconds (currently, <code>30000L</code>).</p> <p>What happens, is that if I connect <code>Settings.MAX_NUMBER_OF_PLAYERS</code> clients, everything is fine (exit because of <code>for</code> condition), but if I don't, the <code>SocketTimeoutException</code> I'd expect is never thrown and the server hangs forever.</p> <p>If I understand right, <code>server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS);</code> should be sufficient, but it doesn't give the expected behaviour.</p> <p>So, can anyone spot the error here?</p>