protected final int blockingRead ( ) throws ClosedChannelException , IOException { int n = 0 ; int readCount = 0 ; Selector readSelector = SelectorFactory . getSelector ( ) ; SelectionKey tmpKey = null ; try { if ( this . selectableChannel . isOpen ( ) ) { tmpKey = this . selectableChannel . register ( readSelector , 0 ) ; tmpKey . interestOps ( tmpKey . interestOps ( ) | SelectionKey . OP_READ ) ; int code = readSelector . select ( 500 ) ; tmpKey . interestOps ( tmpKey . interestOps ( ) & ~ SelectionKey . OP_READ ) ; if ( code > 0 ) { do { n = ( ( ReadableByteChannel ) this . selectableChannel ) . read ( this . readBuffer . buf ( ) ) ; readCount += n ; if ( log . isDebugEnabled ( ) ) { log . debug ( "use temp selector read " + n + " bytes" ) ; } } while ( n > 0 && this . readBuffer . hasRemaining ( ) ) ; if ( readCount > 0 ) { decodeAndDispatch ( ) ; } } } } finally { if ( tmpKey != null ) { tmpKey . cancel ( ) ; tmpKey = null ; } if ( readSelector != null ) { // Cancel the key. readSelector . selectNow ( ) ; SelectorFactory . returnSelector ( readSelector ) ; } } return readCount ; }
Blocking read using temp selector