Search code examples
javanio

ByteBuffer and partial write


If the ByteBuffer is written partially, the position is updated and the next _channel.write call will resume from last position, yep?

compact() is not necessary?

private AsynchronousSocketChannel _channel;
private ByteBuffer _buffer;

final CompletionHandler<Integer, LogstashClientStream> _writeCompletionHandler = new CompletionHandler<Integer, LogstashClientStream>(){
    @Override
    public void completed(Integer sent, LogstashClientStream self) {
        if( _buffer.remaining() == 0 ){
            _buffer.clear();
            //...
        }                       
        else {
            // partial write
            self.send();
        }
    }

    @Override
    public void failed(Throwable exc, LogstashClientStream self) {
        //...
    }
};

private void send(){
    try{
        _channel.write( _buffer, this, _writeCompletionHandler);
    } catch(Throwable e){
        //...
    }
}

Solution

  • Yes, it will resume, and no, compact() is not necessary here. It's useful mainly in cases when you want to fill the rest of the buffer from some input stream before invoking write() again.