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");

  • Ethan
    I tried this and had my native code (of process A) lock the file and didn't release the lock. Next i tried aquiring the lock in java code (of process B) and it was able to aquire the lock. Does this work only within the same process or across processes?
  • Thanks for the article!
  • 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!
  • 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.
blog comments powered by Disqus