Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileLock changes between java 5 and java 6

In Java 1.5, java.nio.channels.FileLock did not check to see files that were already locked. Referenced Here

The snippet states:

The java.nio.channels.FileLock class checks for files already locked by other FileChannel instances

Java SE 6 throws an OverlappingFileLockException if an application attempts to lock a region that overlaps a region locked through another FileChannel instance. Previous versions did not check for file locks obtained by other FileChannel instances. By default the java.nio.channels.FileChannel.lock method checks if the requested lock overlaps with a region held by this Java virtual machine.

So in pre-Java 6, exclusive file locking didn't work if you had multiple programs writing to the same file (with each program attempting to get an exclusive lock). How did people get around this with Java 5 and before?

like image 321
bogertron Avatar asked May 07 '26 21:05

bogertron


1 Answers

I don't think Java5's behavior is a serious problem.

Consider an OS that associates a file lock with a process. If a process already owns a file lock, when it requests the lock again, OS can grant it without error. It's a "reentrant" lock in a sense. It prevents two processes from locking the same file at the same time, and it's up to a process to make sure that when it has the lock, it doesn't have two threads doing some overlapping changes to the file.

In a JVM usually there are lots of independent packages, there must be use cases that two packages try to lock the same file. If they are all granted the lock, we got a problem. It's difficult to ask the two independent packages to cooperate in some way, hence Java6 shrink the ownership from whole process to a channel. (hopefully the two packages will not share the same channel)

Yet such use cases are probably not very common. Usually a file is of some special kind that will only be handled by a certain package. Imagine a database package, its files are not likely touched by other packages in the same JVM, but may be touched by the same package in other JVMs. So Java5's behavior would be fine in this case, and such cases are probably the majority.

like image 139
irreputable Avatar answered May 09 '26 10:05

irreputable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!