Re: File Locking Question
alejandrina wrote:
Hi,
I am trying to use Java's FileLock class to synchronize writing to a
file **across machines**. The file resides on a file server. Under
Windows, it works perfectly (ie, only one machine at a time can gain
access, the others wait,no clobbered file, everything is written in
order). Under Linux (same code) the file gets clobbered. No exceptions
are thrown.
Can anyone offer suggestions??
Here is the critical code segment:
//lock the file and wait till we can
FileChannel channel = fos.getChannel();
FileLock lock = null;
try {
while ((lock = channel.tryLock()) == null) {
System.out.println (Utils.getHostname() + " Failed lock...wait");
Thread.sleep(100);
}
System.out.println (Utils.getHostname() + " Locked:" + lock);
System.out.println (Utils.getHostname() + " Lock type is "+
((lock.isShared())?"shared":"exclusive"));
System.out.println (Utils.getHostname() + " Is lock valid: " +
lock.isValid());
//write the title first if noone's done it
//and they asked for one
if (channel.size() <= 0 && bbTitle != null)
channel.write (bbTitle);
channel.write(bb);
} catch (Exception e) {
throw (e);
} finally {
if (lock != null) {
System.out.println (Utils.getHostname() + " Releasing lock");
lock.release();
}
}
This is the exact same code you posted the last time and a synonomous
question. I suspect the answers you got are still valid.
To recap, it seems the Linux locks are advisory and the Windows locks are
mandatory. Unless you control the processes that "clobber" your data, you're
not going to be able to enforce a lock. Are you able to write a "resource
manager" server to control the file, as was suggested before? Did you try
Patricia Shanahan's answer, and did it in any way affect the outcome?
--
Lew