views:

101

answers:

1

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?

+2  A: 

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.

Aaron Digulla
EDITED: Creating of a directory is not an option since other programs should be able to read the contents of the file. Locking/unlocking takes place only during update.
ZiG
Why isn't this an option? Other programs needn't care about the directory (you needn't put the file inside that directory).
sfussenegger
Correct me if I got it wrong. So I am gonna create a directory and lock it when the file needs to be updated rather than locking the file?
ZiG
You can't lock directories. The directory *is* the lock. When the directory exists, F is locked. Every program must create the directory (and wait until it disappears), then read/modify F and then delete the directory again.
Aaron Digulla