Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

java.nio, FileChannel, FileLock conundrum...

807591Oct 20 2006 — edited Jun 2 2008
Hey all--

I want to have multiple java machines on multiple clients to access a singe file. I want the first java machine to access it to lock the file so only it can write to the file. Other machines may come in later and read it.

Here's the trouble. If I simply access the file as, say, a RandomAccessFile in "rw" mode. All the clients may read and write to their hearts desire without throwing and exception.

So I found that if I obtain a FileChannel from the RandomAccessFile, I can tryLock(0,Long.MAX_VALUE,true) to obtain a Shared Lock.

Here's the trouble. A client can obtain the lock and prevent others from writing to it successfully while allowing them to read from it...great!. HOWEVER, even though that particular client has the lock, the client can't write to the file either!
myRandomAccessFile.write()
methods NOR
myRandomAccessFile.getChannel().write(myByteBuffer);
NOR
FileLock myFileLock =myRandomAccessFile.getChannel().tryLock(0,Long.MAX_VALUE,true);
FileChannel lockedChannel = myFileLock.channel();
lockedChannel.write(myByteBuffer);
all of these throw a java.io.IOException "The process cannot access the file because another process has locked a portion of the file"

I'm only running one process and one virtual machine. I also checked to make sure myFileLock != null and that myFileLock.isValid()==true So does obtaining a filelock also prevent my OWN program from writing to the file?! If so what's the use of a filelock? Because in order to write to the channel upon whose lock I have, I'd have to release the lock which would allow any other clients the ability to write to it concurrently.

Thanks for the help! The documentation seems a bit sparse on this...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 30 2008
Added on Oct 20 2006
9 comments
1,662 views