> There was a recent thread discussing that Java file locks may be
> advisory only, depending on how the underlying OS implements file locks.
Write once, test everywhere. Just great. The Java Doc says this about
FileLock:
" Whether or not a lock actually prevents another program from accessing
the content of the locked region is system-dependent and therefore
unspecified. The native file-locking facilities of some systems are
merely advisory, meaning that programs must cooperatively observe a
known locking protocol in order to guarantee data integrity. On other
systems native file locks are mandatory, meaning that if one program
locks a region of a file then other programs are actually prevented from
accessing that region in a way that would violate the lock. On yet other
systems, whether native file locks are advisory or mandatory is
configurable on a per-file basis. To ensure consistent and correct
behavior across platforms, it is strongly recommended that the locks
provided by this API be used as if they were advisory locks. "
Which to me implies that one should test for a lock first. Writing data
to a locked region and expecting an error to be thrown may not produce
an exception, just bad data. So it should all still work, you just have
to test for locks first. Correct?
Esmond Pitt - 23 Jul 2007 01:51 GMT
> To ensure consistent and correct
> behavior across platforms, it is strongly recommended that the locks
[quoted text clipped - 4 lines]
> an exception, just bad data. So it should all still work, you just have
> to test for locks first. Correct?
Correct. And note that Unix 'mandatory' locks, where implemented, would
only have made the situation worse. With Unix mandatory locks, if the
writer hadn't tried to acquire the lock first, the write would be merely
*delayed* until the lock was released by whoever had it, *ensuring* a
data corruption (because the non-cooperative update occurred after the
cooperative update). By contrast, that non-cooperative write() on a
Windows machine would have given an error immediately, which is the only
sensible behaviour. You must always test and set file locks in all parts
of an application that want to share a file, and *never* rely on Unix
mandatory locking even when you know it exists.