Search code examples
javafilelockingfile-lockingunlock

Locking and Updating a File Accordingly


Note: I have read other posts on how to lock and unlock a file. I didn't find anything special that I wasn't aware of. So I am gonna put my scenario here to better appreciate the problem on hand.

In my experience, FileChannel.lock doesn't guarantee locking and unlocking of a File when different Objects from multiple instances of jvm are trying to lock and update the file.

The scenario in my application is - there are three separate programs that update a file. Those programs are being run on different jvm instances. Say the programs are A, B, and C; and the file is F. If A locks the file F, B and C should wait for F to be released before one of the other programs can get a hold of it. This works fine if the programs are run on the same jvm instance. Unfortunately this doesn't work in multiple jvm instances.

I had another idea which was to have a flat file where I'd indicate if F should be updated. The content of that flat file can be either LOCKED or UNLOCKED. Default/initial value would be UNLOCKED. So, when one of the programs would want to update F, it needs to see the flag in the flat file. If flag reads LOCKED, it should wait. In this approach, there's a problem though - what if multiple programs open the flat file exactly at the same time and see "UNLOCKED" or two programs that were waiting for the flat file to read UNLOCKED and exactly at the same time see file reads "UNLOCKED"?

Any idea?


Solution

  • If you need locking in a filesystem, then you must create a directory. Directory exists means "locked", missing directory means unlocked.

    The reason is that creating and deleting directories must be atomic operations in any filesystem. So as soon as two processes try to create the same directory, one of them will get an error.