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 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?

2
  • 1
    Have ever looked at Lucene's implementation of org.apache.lucene.store.Lock (e.g. SimpleFSLock and NativeFSLock)? Those classes are made for the exact same purpose, so maybe you get some ideas from there. Commented Oct 22, 2009 at 15:41
  • Sounds cool.. I am gonna take a look. Thanks a million. Commented Oct 22, 2009 at 15:43

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why isn't this an option? Other programs needn't care about the directory (you needn't put the file inside that directory).
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.