JDK 1.4 adds a number of advanced features related to I/O and filesystems. The more advanced I/O features are often non-portable or only partially portable. File locking is one of these features. While most operating systems provide some form of file locking, file locking isn't implemented exactly the same way on every platform.
For a general example of file locking in Java, review the following code snippet. It locks the first 10 bytes of a file called "foo.txt":
RandomAccessFile raf =
new RandomAccessFile( "foo.txt", "rw" );
FileChannel fc = raf.getChannel();
FileLock lock = fc.lock( 0, 10, false );
This is an exclusive lock, which means that no one else can acquire a lock on this same region until it is released:
The idea is that only one exclusive lock can exist on any particular region of a file at any given time. You cannot acquire an exclusive lock on a region that overlaps a region that is already locked with another exclusive lock (see Figure 1).
This file-locking facility also provides shared locks, which allow more than one shared lock on the same region of a fileas long as no exclusive locks are overlapping the same region.
Because platforms don't all implement file locking in the same way, the JDK file-locking facility is not identical on each platform. It may have a number of differences:
- Locks may or may not be advisory. An advisory lock does not actually prevent access to the thing locked, it prevents only other locks from being acquired. This may sound confusing, but it's probably familiar to youthe locks used in Java for the synchronized keyword are advisory locks.
- Shared locks may not be available. A platform might have only exclusive locks. For many applications, this is okay. The only side effect is that some systems run more slowly. Strictly speaking, however, shared and exclusive locks have different semantics so this isn't a trivial point.
- Locks may be process-specific. Locks held in one process may or may not affect locking activity in other processes. While it is increasingly common for locks to be system-wide, locks may be only process-wide in older operating systems.
In a practical sense, the last of these three issues is the most immediate. Locks are most often used to prevent data corruption in files to which multiple entities are writing. If locks are only process-wide, then multiple processes can potentially corrupt data. I'll examine a solution to this problem in the following sections.