Thursday, October 29, 2009

Locking a file in Java

Locking a file in Java is platform dependent. Write once run anywhere? Thumbs down. Some platforms will not allow a file access without a lock while others will.


This is very useful especially when writing your own database (I know some people will argue but this is still happening in corporations handling very sensitive data). It starts with a simple file access.



try {
final File file = new File("Tables.dat");
final FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();

// this method will block until a lock is acquired
final FileLock lock =fileChannel.lock();

// this method will not block, it will return null or throw an exception
lock = fileChannel.tryLock();

// TODO: do something with the file

// release the lock
lock.release();

// cleanup / close file
fileChannel.close();
} catch (Exception e) {
// TODO: handle exception
}

Caution: You really need to verify how the target platform handles files. This will not apply on a distributed database as well as networked file systems, if that’s the case you need to write at least a protocol for handling concurrency.

No comments: