Java of Evil: FileLock

Currently I am in a phase of “lots of work” which means I do not find time for blogging because I have only three states of being: working, being tired and sleeping. But I found out lots of fancy things about java.

Yesterday I implemented file locking using the java.nio package. Do not use java.io.File.createNewFile(...) to create file locks. It is not safe! It says so in the api docs and links to the nio package.

I now have a nice little class the returns vm-wide locks on files or lists of files and releases them on demand. Neat: except it didn’t solve my problem.

public static FileLock lock(final String filename) 
throws IOException {
    final RandomAccessFile file =
          new RandomAccessFile(new File(filename), "rw");
    final FileChannel channel = file.getChannel();    
    return channel.lock();       
}

By the way there is also a method tryLock() which tries to lock but does not block as lock() does. Here’s the release method:

public static void release(final FileLock lock) 
throws IOException {
        if(lock.isValid()) { 
            lock.release(); 
            lock.channel().close(); 
        } else { 
            LOG.warn("Trying to release invalid lock"); 
        } 
}

A colleague requested I post this somewhere when I found out how the java FileLock class worked. I think it works. But it does not necessarily solve any problems. How does the java.nio package interact with the java.io package for example?