Harold Yarmouth wrote:
> RandomAccessFile raf = new RandomAccessFile(file, "rw");
> FileLock fileLock = raf.getChannel().lock();
> Reader reader = new FileReader(file);
> int ch = reader.read();
>
> causes
>
> java.io.IOException: The process cannot access the file because another
> process has locked a portion of the file
>
> That is incorrect. It is the same process, not another process, that has
> locked a portion of the file.
>
> From FileLock's Javadoc:
>
> File locks are held on behalf of the entire Java virtual machine. They
> are not suitable for controlling access to a file by multiple threads
> within the same virtual machine.
>
>
> This strongly implies that the IOException is in error: the JVM holding
> a file lock should not inhibit the same JVM from opening the same file
> in another manner.
I've done some Googling and there is one other report of this behavior,
which seems to concur that it's buggy. It's at
http://www.velocityreviews.com/forum...putstream.html
and does not suggest a workaround.
I can't seem to find any workaround save to not use FileLock at all, or
only use shared locks (and therefore not use FileLock at all on some
platforms -- every lock would have to be requested shared, tested for
actually coming out exclusive, and discarded if so).
What a pain. I think I may just get rid of using file locks and pray no
other process scribbles on the file while my application is making
changes, or relies on it being in a consistent state.
It looks like Java still has no really good way to manage file locking
in a way that supports making complex file manipulations appear atomic
to other processes, while also supporting implementing them arbitrarily
within the one JVM (if necessary, using ordinary synchronized, wait, and
notify on a suitably-chosen object to make them appear atomic to other
threads within the JVM).