Java File Locking: FileLock, Shared and Exclusive Locks
Coordinate processes that share a file with Java's FileChannel.lock and tryLock: exclusive and shared locks, locking regions, releasing with try-with-resources, a locked read-modify-write update, OverlappingFileLockException, and the platform caveats such as advisory locks on Linux.
kvi5hnuCode Sprout team member8 min readOn this page
When several programs modify the same file at the same time, the file can easily end up corrupted. Imagine two instances of an application both reading a settings file, each adding an entry, and each writing the file back. The second write silently discards the first one's change. Within one Java program, you coordinate threads with locks (Volume I, Part 10). Between processes, the operating system offers file locks, and Java exposes them through FileChannel.
Acquiring a lock
Open a channel to the file and call lock or tryLock:
FileChannel channel = FileChannel.open(path, READ, WRITE);
FileLock lock = channel.lock(); // waits until the lock is available
FileLock lock = channel.tryLock(); // returns at once: a lock, or null if someone else holds one
The file stays locked until you call release() (or close(), which does the same) on the lock, or close the channel. FileLock implements AutoCloseable, so try-with-resources is the natural form. Since the lock variable itself isn't used, it can be unnamed (Java 22):
try (FileLock _ = channel.lock()) {
// read, modify and write the file
}
Exclusive and shared locks, and regions
The no-argument methods lock the whole file exclusively. You can also lock a region, and choose the kind of lock:
FileLock lock(long position, long size, boolean shared)
FileLock tryLock(long position, long size, boolean shared)
- An exclusive lock (
shared = false) keeps every other process from locking an overlapping region. It requires a channel opened for writing, or you getNonWritableChannelException. - A shared lock (
shared = true) lets other processes take shared locks on the same region too, but no exclusive ones. That's the classic readers-writer arrangement. It requires a channel opened for reading. - Not all systems support shared locks. You may get an exclusive lock when you ask for a shared one.
isShared()tells you what you actually got. - A region doesn't have to lie within the current file. If you lock the end of a file and the file grows, the new bytes aren't covered. To cover the whole file however large it gets, use position 0 and size
Long.MAX_VALUE, which is what the no-argument methods do.
A locked update
The demo stores user entries in a properties file. Each register call reads the file, updates one entry and writes everything back, all while holding an exclusive lock, so concurrent processes can't interleave their updates:
try (FileChannel channel = FileChannel.open(path, READ, WRITE, CREATE);
FileLock _ = channel.lock()) {
var buffer = ByteBuffer.allocate((int) channel.size());
while (buffer.hasRemaining() && channel.read(buffer) != -1) { }
var props = new Properties();
props.load(new StringReader(new String(buffer.array(), StandardCharsets.UTF_8)));
props.setProperty(user, value);
var out = new StringWriter();
props.store(out, null);
channel.truncate(0);
channel.position(0);
channel.write(ByteBuffer.wrap(out.toString().getBytes(StandardCharsets.UTF_8)));
}
This shows the main inconvenience of the API: locks live on FileChannel, which works with ByteBuffers, so you convert between buffers and readers or writers by hand. Note the explicit position(0) after truncate, and that you must read and write through the locked channel. Opening a second stream on the file would bypass the lock and, on some systems, closing it would release the lock.
In a real application, the entries would be password hashes, not passwords. Article 83 shows how to hash passwords properly.
Caveats
File locking depends heavily on the operating system. Keep these points in mind:
- Locks are often advisory. On Linux and macOS, a lock stops other processes only if they also ask for a lock. A program that doesn't lock can still read and write the file. Windows enforces locks more strictly: other processes can't write to locked regions.
- Locks belong to the whole JVM, not to a thread. Two threads in one program can't both lock the same file: the second
lockortryLockthrowsOverlappingFileLockExceptioninstead of waiting. Coordinate threads within one JVM with ordinary Java locks, and use file locks only between processes. - Closing a channel may release all locks that the JVM holds on the file, even locks acquired through other channels. Avoid having several channels open on a locked file.
- On some systems, you can't map a locked file into memory, or lock a mapped one.
- Locking files on network file systems is unreliable. Avoid it.
- Java uses the operating system's native locks, so programs in other languages that use the same mechanism see them. But some systems offer several independent mechanisms: on Linux, Java uses POSIX
fcntllocks, which don't interact with locks taken throughflock(), so a native program usingflockwon't be stopped.
A complete example
The demo can show only the behavior within one JVM, but it demonstrates every part of the API, including the OverlappingFileLockException you get when the same JVM tries to lock a file twice. To see locking between processes, run several copies of a program that calls register at the same time. Every update survives.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import static java.nio.file.StandardOpenOption.*;
public class Solution {
// read-modify-write of a properties file while holding an exclusive lock
static void register(Path path, String user, String value) throws IOException {
try (FileChannel channel = FileChannel.open(path, READ, WRITE, CREATE);
FileLock _ = channel.lock()) {
var buffer = ByteBuffer.allocate((int) channel.size());
while (buffer.hasRemaining() && channel.read(buffer) != -1) { }
var props = new Properties();
props.load(new StringReader(new String(buffer.array(), StandardCharsets.UTF_8)));
props.setProperty(user, value);
var out = new StringWriter();
props.store(out, null);
String text = out.toString().lines().filter(l -> !l.startsWith("#")).sorted()
.reduce("", (a, b) -> a + b + "\n"); // drop the timestamp comment, sort for stable output
channel.truncate(0);
channel.position(0);
channel.write(ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8)));
channel.force(true);
}
}
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("locked", ".properties");
register(file, "alice", "hash1");
register(file, "bob", "hash2");
register(file, "alice", "hash3");
System.out.print("file contents:\n" + Files.readString(file));
try (FileChannel channel = FileChannel.open(file, READ, WRITE)) {
// an exclusive lock on the whole file
FileLock lock = channel.lock();
System.out.println("locked: valid=" + lock.isValid() + ", shared=" + lock.isShared()
+ ", position=" + lock.position() + ", size=" + (lock.size() == Long.MAX_VALUE ? "Long.MAX_VALUE" : lock.size()));
// locks belong to the whole JVM: a second attempt from this JVM fails at once
try (FileChannel other = FileChannel.open(file, READ, WRITE)) {
other.tryLock();
} catch (OverlappingFileLockException e) {
System.out.println("second lock in the same JVM: OverlappingFileLockException");
}
lock.release();
System.out.println("after release: valid=" + lock.isValid());
// locking separate regions is fine
try (FileLock first = channel.lock(0, 10, false); FileLock second = channel.lock(10, 10, false)) {
System.out.println("regions [0,10) and [10,20) locked: " + (first.isValid() && second.isValid())
+ ", overlap: " + first.overlaps(10, 10));
}
// shared locks are for readers; the OS may give you an exclusive one instead
try (FileLock shared = channel.lock(0, Long.MAX_VALUE, true)) {
System.out.println("requested a shared lock, got shared=" + shared.isShared());
}
// tryLock returns immediately: a lock, or null if another process holds one
try (FileLock attempt = channel.tryLock()) {
System.out.println("tryLock succeeded: " + (attempt != null));
}
}
// a shared lock needs a channel opened for reading, an exclusive one for writing
try (FileChannel readOnly = FileChannel.open(file, READ)) {
readOnly.lock();
} catch (NonWritableChannelException e) {
System.out.println("exclusive lock on a read-only channel: NonWritableChannelException");
}
// closing the channel releases its locks
FileLock leftover;
try (FileChannel channel = FileChannel.open(file, READ, WRITE)) {
leftover = channel.lock();
}
System.out.println("lock valid after its channel closed: " + leftover.isValid());
Files.delete(file);
}
}
file contents:
alice=hash3
bob=hash2
locked: valid=true, shared=false, position=0, size=Long.MAX_VALUE
second lock in the same JVM: OverlappingFileLockException
after release: valid=false
regions [0,10) and [10,20) locked: true, overlap: false
requested a shared lock, got shared=true
tryLock succeeded: true
exclusive lock on a read-only channel: NonWritableChannelException
lock valid after its channel closed: false
Common questions
How do I make sure only one instance of my application runs?
Open a lock file in the application's data directory and call tryLock() on its channel at startup. If it returns null, another instance holds the lock. Keep the channel open for the whole run. The operating system releases the lock when the process ends, even after a crash, which makes this more robust than a marker file that a crashed instance leaves behind.
What happens to a lock if my program crashes? The operating system releases it when the process dies, because locks belong to the process's open file. That is a major advantage over "lock files" whose mere existence means locked.
Does a lock stop other programs from reading the file on Linux? No. Locks on Linux and macOS are advisory: programs that do not ask for a lock can still read and write. Only cooperating programs that all lock the file are protected.
Can I use a file lock to synchronize threads in my own program?
No. Within one JVM, a second lock attempt throws OverlappingFileLockException instead of waiting. Use ReentrantLock, synchronized or other concurrency tools for threads, and a single file lock held by the JVM for coordination with other processes.
lock() blocks forever. How do I wait with a timeout?
There is no timed lock. Call tryLock() in a loop with short sleeps until it succeeds or your deadline passes.
API reference
java.nio.channels.FileChannel
| Method | Description |
|---|---|
FileLock lock() | an exclusive lock on the whole file; blocks until acquired |
FileLock tryLock() | an exclusive lock on the whole file, or null if unavailable |
FileLock lock(long position, long size, boolean shared) | locks a region; blocks until acquired |
FileLock tryLock(long position, long size, boolean shared) | locks a region, or returns null |
FileChannel truncate(long size) | shrinks the file to size if it's larger |
FileChannel position(long newPosition) | sets the channel's read/write position |
void force(boolean metaData) | writes changes (and optionally metadata) to the storage device |
java.nio.channels.FileLock
| Method | Description |
|---|---|
void release(), void close() (Java 7) | releases the lock |
boolean isValid() | whether the lock is still held |
boolean isShared() | whether the lock is shared |
long position(), long size() | the locked region |
boolean overlaps(long position, long size) | whether the lock overlaps a region |
Summary
- File locks coordinate processes that update the same file. Get them from a
FileChannelwithlock(blocking) ortryLock(non-blocking, may returnnull). - Exclusive locks need a writable channel and shared locks a readable one. Regions can be locked separately, and
Long.MAX_VALUEcovers future growth. - Release locks with try-with-resources. Read and write through the locked channel.
- Locks are per JVM, so a second lock attempt in the same JVM throws
OverlappingFileLockException. They're advisory on many systems, unreliable on network file systems, and closing any channel may release them. - Often an atomic move, an atomic
createFile, or a database is the simpler solution.
Practice Questions
What's the difference between channel.lock() and channel.tryLock()?
lock() blocks until the lock can be acquired. tryLock() returns immediately, with the lock if it was available and null if another process holds a conflicting lock.
Two threads in the same program call channel.lock() on the same file. What happens?
The second call throws OverlappingFileLockException. File locks are held on behalf of the whole JVM, so they can't coordinate threads within it. Use ReentrantLock or synchronized for that.
On Linux, process A holds an exclusive lock on data.txt. Can process B, which never calls lock(), write to the file?
Yes. Locks on Linux are advisory: they only affect processes that also request locks. All programs that access the file must cooperate by locking it.
Why does the demo call channel.position(0) after channel.truncate(0)?
After reading, the channel's position is at the old end of the file. truncate(0) does clamp a position beyond the new size, so here it would already be 0, but that's an easily overlooked detail of truncate. Calling position(0) states the intent, writing the new contents from the start, and keeps the code correct if it's later changed to truncate to a different size.
How do you lock a file so that many readers can proceed at once but writers wait?
Readers take shared locks with channel.lock(0, Long.MAX_VALUE, true) on channels opened for reading. Writers take exclusive locks with channel.lock() on channels opened for writing. Check isShared(), because some systems don't support shared locks and hand out exclusive ones instead.
Previous: Java NIO Buffers: Capacity, Position, Limit, flip and compact
Related reading
- Java Parallel Streams: When They Help, Ordering and Thread Safety
- Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
- Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
- Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
- Java Race Conditions and ReentrantLock: Synchronizing Shared Data

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.