Search code examples
javamultithreadingsocketsnetwork-programmingnio

NIO Reactor Pattern: Receiving asynchronous callbacks inside the selector loop every N miliseconds


I was wondering what is the standard/best implementation of that in Java NIO. This is fundamental to implement something like heartbeats every N seconds, etc. Note: For obvious reasons (threads are evil and context switches are slow) everything must always happens inside the selector loop.

Note1: Answering Apache MINA does not count, unless you and the framework can demonstrate a clear scenario where this is done in a KISS (Keep It Simple Stupid) way.

Note2: Pipes require threads.


Solution

  • Not sure why you wouldn't have a background thread for sending heartbeats or timing out connections. Heartbeats are not generally considered performance critical.

    You can have the selector wait a specific amount of time and send heartbeats and check time outs at intervals.

    Do you mean like

    selector.select(timeout);
    
    if (System.currentTimeMS() > sendHeartbeatTime) {
        for(Connection conn: connections) 
            conn.checkAndSendHeartbeat();
    }
    
    // in Connection
    private long lastSend = System.currentTimeMS();
    private long lastRead = System.currentTimeMS();
    
    public void writeData() {
       lastSend = System.currentTimeMS();
       // write data.
    }
    
    public void checkAndSendHeartbeat() {
       long now = System.currentTimeMS();
       if (now - lastRead > HEARTBEAT_TIMEOUT) {
          closeConnection();
       else if (now - lastSend > HEATBEAT_INTERVAL)
          writeHeartBeatData();
    }