header

Torsten Curdt’s weblog

Native file locks in java

Java 1.4 introduced the native io layer into the JDK. One of the nice things you can do with it is to execute a native file lock that gets acknowledged by both “fcntl”- and “flock”-style locking. This is tremendously helpful if you need to share resources with native programs. So what is in C


  int fd = open("/path/to/file", O_RDWR);

  if (flock(fd,LOCK_EX) != 0 ) { ... }

  printf("locked file\\npress return");
  char c = getchar();

  if (flock(fd,LOCK_UN) != 0 ) { ... }

  printf("released file\\n");
  close(fd);

  int fd = open("/path/to/file", O_RDWR);

  struct flock lock;
  lock.l_type = F_WRLCK;
  lock.l_whence = SEEK_SET;
  lock.l_start = 0;
  lock.l_len = 0;
  lock.l_pid = 0;

  if (fcntl(fd, F_SETLK, &lock) == -1) { ... }

  printf("locked file\\npress return");
  char c = getchar();

  lock.l_type = F_UNLCK;

  if (fcntl(fd, F_SETLK, &lock) == -1) { ... }

  printf("released file\\n");
  close(fd);

becomes this in java


File file = new File("/path/to/file");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.lock();

System.out.println("locked file\\npress return");
System.in.read();

lock.release();
System.out.println("released file\\n");

3 Responses to “Native file locks in java”

  1. Gunnar said, on 5. April 2007 at 7:38

    You can’t get a FileChannel from a File, i.e. there is no File#getChannel method. But you can get one from an FileOutputStream.

  2. tcurdt said, on 5. April 2007 at 9:04

    Sure, that was an error. You either get the channel from the streams or you wrap the file in a RandomAccessFile. I have fixed that now. Thanks for the heads up!

  3. Achim said, on 22. June 2007 at 7:30

    Thanks for the article!

Leave a Reply

Please copy the string qvFIAu to the field below: