A FileLock represents a lock on a region of a file held through a channel. It coordinates only participants that honor the same locking protocol, and platform behavior for other writers can differ.
Java FileLock: coordinate one byte range with a shared protocol
Operational contract
This writer takes an exclusive lock on one byte, writes a single-byte status at position zero, and releases the lock in a try-with-resources scope. It deliberately keeps the critical section short. Another lock on an overlapping range in the same JVM may fail with OverlappingFileLockException rather than wait, while another process may wait or observe platform-specific behavior. A lock is not a substitute for validating file ownership or making a multi-file transaction. The path still needs an access-control policy.
Failure case
Two depot processes update a one-byte handoff marker. Both agree to lock range [0,1) before writing. If one process skips that protocol, the lock cannot make its write safe. If the marker needs a richer state transition, a database transaction or atomic file publication may be a better fit than extending the locked section around unrelated work.
Java code
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class HandoffMarkerLock {
public static void mark(Path marker, byte status) throws IOException {
try (FileChannel channel = FileChannel.open(marker,
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
FileLock held = channel.lock(0, 1, false)) {
ByteBuffer update = ByteBuffer.wrap(new byte[] {status});
if (channel.write(update, 0) != 1) throw new IOException("Marker update incomplete");
}
}
}Performance and ownership cost
The update is O(1) data work, but lock acquisition can wait indefinitely under contention. A short locked region reduces wait time. The lock and channel consume operating-system resources until closed.
Common Mistakes
- Do not assume nonparticipating writers are stopped on every platform.
- Do not expect an overlapping lock in the same JVM to queue politely.
- Do not hold the lock across slow remote calls.
Connected lessons
- Java Files.move: atomic publication is a filesystem contract
- Java FileChannel.write: finish the buffer before reporting success
- Java JDBC transactions: atomic updates and rollback
- Java positioned FileChannel.read: detect a short record without moving the cursor
- Java FileChannel.transferTo: verify the byte count on every pass
- Java FileChannel.force: distinguish written bytes from forced storage
- Java FileChannel.truncate: cut only after validating the recovery offset
- Java AsynchronousFileChannel: own the buffer through completion
- Java file channels and JVM observations quiz
- Advanced Java
