An implementation of the lock() method with CompletionHandler - Java File Path IO

Java examples for File Path IO:File Lock

Description

An implementation of the lock() method with CompletionHandler

Demo Code

import java.io.IOException;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Main {
  static Thread current;

  public static void main(String[] args) {
    Path path = Paths.get("C:/folder1/", "test.txt");
    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
        .open(path, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
      current = Thread.currentThread();
      asynchronousFileChannel.lock("Lock operation status:",
          new CompletionHandler<FileLock, Object>() {
            @Override/*from  w w  w .  ja  v a2 s  . co  m*/
            public void completed(FileLock result, Object attachment) {
              System.out.println(attachment + " " + result.isValid());
              if (result.isValid()) {
                try {
                  result.release();
                } catch (IOException ex) {
                  System.err.println(ex);
                }
              }
              current.interrupt();
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
              System.out.println(attachment);
              System.out.println("Error:" + exc);
              current.interrupt();
            }
          });

      System.out.println("Waiting... \n");
      try {
        current.join();
      } catch (InterruptedException e) {
      }
      System.out.println("done");

    } catch (Exception ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials