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 so that someone can give some suggestions out.
In my experience, FileChannel.lock doesn't guarantee the situation of 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 seperate programs that update a file. Those programs are 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 onto 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 guys?