Adding AsynchronousFileChannel to a file with Java 7

I am trying to use the AsynchronousFileChannelJAVA 7 API to write a file in an asynchronous way, however I could not find an easy way to add it to the file.

The description of the API states that it AsynchronousFileChanneldoes not support the position of the file, and you must specify the position of the file. This means that you must maintain the global value of the file position. Moreover, this global state must be atomic in order for you to increase properly.

Is there a better way to do updates using AsynchronousFileChannel?

Also, can someone explain the use of the Attachment object in the API?

public abstract <A> void write(ByteBuffer  src,
             long position,
             A attachment,
             CompletionHandler<Integer ,? super A> handler)

The javadoc says: attachment - An object to attach to an I / O operation; may be null

What is the point of using this binding object?

Thanks!

+4
2

?

- , ; . , , .

API- AsynchronousFileChannel JAVA 7 async-, .

Async , - . , , , . , ( "" ):

class WriteOp implements CompletionHandler<Integer, AsynchronousFileChannel> {
  private final ByteBuffer buf;
  private long position;

  WriteOp(ByteBuffer buf, long position) {
    this.buf = buf;
    this.position = position;
  }

  public void completed(Integer result, AsynchronousFileChannel channel) {
    if ( buf.hasRemaining() ) { // incomplete write
      position += result;
      channel.write( buf, position, channel, this );
    }
  }

  public void failed(Throwable ex, AsynchronousFileChannel channel) {
    // ?
  }
}

class AsyncAppender {
  private final AsynchronousFileChannel channel;
  /** Where new append operations are told to start writing. */
  private final AtomicLong projectedSize;

  AsyncAppender(AsynchronousFileChannel channel) throws IOException {
    this.channel = channel;
    this.projectedSize = new AtomicLong(channel.size());
  }

  public void append(ByteBuffer buf) {
    final int buflen = buf.remaining();
    long size;
    do {
      size = projectedSize.get();
    while ( !projectedSize.compareAndSet(size, size + buflen) );

    channel.write( buf, position, channel, new WriteOp(buf, size) );
  }
}
+3

channel.size() . , , , , .

- , , , .

0

All Articles