Skip to content
javahacks.dev
Microservices

How to Implement Distributed Locks in Java Services

Implement distributed locks in Java: why a JVM lock is not enough, Redis and database options, lease expiry, fencing tokens and when to avoid locks entirely.

7 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, IntelliJ IDEA, Linux and JUnit5 logos.

Two instances of the same service both run the nightly job, or both charge the same invoice. A local lock cannot help, because each JVM has its own. A distributed lock coordinates through a shared system. Before using one, check that the work cannot be made idempotent, since that is simpler and safer. This uses Java 25 and Spring Boot 4.

Option 1: database lock

If you already have a relational database, use it.

java
@Transactional
public void runNightly() {
    boolean got = jdbc.queryForObject(
            "select pg_try_advisory_xact_lock(?)", Boolean.class, 42L);
    if (!got) return;                 // another instance holds it
    doJob();
}

pg_try_advisory_xact_lock takes an application level lock released at the end of the transaction, so a crash releases it automatically when the connection drops. For MySQL, GET_LOCK is the counterpart. Another form is select ... for update skip locked on a row that represents the work, which also distributes tasks among workers. The deadlock and isolation rules are in database deadlocks.

Option 2: Redis

java
String key = "lock:invoice:" + invoiceId;
String token = UUID.randomUUID().toString();

Boolean acquired = redis.opsForValue().setIfAbsent(key, token, Duration.ofSeconds(30));
if (Boolean.TRUE.equals(acquired)) {
    try {
        process(invoiceId);
    } finally {
        // release only if we still own it
        redis.execute(RELEASE_SCRIPT, List.of(key), token);
    }
}
lua
if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end

SET key value NX PX 30000 is atomic: it sets the key only if it does not exist, with an expiry. The token identifies the owner, and the script deletes the key only if the token still matches, so a slow holder cannot delete a lock that expired and was taken by another. Libraries such as Redisson wrap this with renewal and re-entrancy.

The hard part: leases expire

An expiry prevents a crashed holder from blocking forever, and creates a worse problem. A holder that is paused, by a long GC pause or a network stall, can wake up after its lease expired and still believe it holds the lock. Two processes now write at once. A timeout cannot fix this, because the pause can come after the last check. See GC pauses.

The remedy is a fencing token: a number that increases with each lock grant, passed to the protected resource, which rejects any write carrying a token lower than one it has seen.

SQL
update invoice set status = 'PAID', fence = :token
where id = :id and fence < :token;

If the stale holder's write arrives after the new holder's, the where clause matches nothing. The lock then only reduces contention, and the fence supplies correctness. Martin Kleppmann's analysis of Redis locks makes this argument in detail.

Option 3: coordination services

ZooKeeper (through Apache Curator) and etcd offer sessions and ephemeral nodes, with stronger semantics than a single Redis node. Use them when you already run them. Do not add a cluster for one lock.

Scheduled jobs: ShedLock

java
@Scheduled(cron = "0 0 2 * * *")
@SchedulerLock(name = "nightlyReport", lockAtMostFor = "30m", lockAtLeastFor = "1m")
public void nightlyReport() { /* runs on one instance */ }

ShedLock stores the lock in a table, Redis or another store and handles the lease for you. For a recurring leader based design, see leader election.

Avoiding locks

Use unique constraints and upserts so a duplicate attempt fails harmlessly. Partition work by key so each key has one owner, as in Kafka consumer groups. Use optimistic version checks, covered in stale object state.

The database lock, shown with two connections

If your service already uses PostgreSQL, an advisory lock is the lowest-effort distributed lock, and its behaviour is easy to show. This program takes locks from two connections, which stand in for two service instances.

Lock.javajava
try (Connection a = DriverManager.getConnection(url); Connection b = DriverManager.getConnection(url)) {
    System.out.println("A takes lock 42      : " + tryLock(a, 42));
    System.out.println("B takes lock 42      : " + tryLock(b, 42));
    System.out.println("B takes lock 43      : " + tryLock(b, 43) + " (a different key)");
    a.close();
    Thread.sleep(200);
    System.out.println("B after A disconnects: " + tryLock(b, 42));
}
Text
A takes lock 42      : true
B takes lock 42      : false
B takes lock 43      : true (a different key)
B after A disconnects: true

Four properties are visible. The lock is exclusive per key: B could not take 42 while A held it. Different keys are independent. pg_try_advisory_lock returns immediately, so the caller decides what to do when it loses, which is usually "skip this run". And the lock was released when A's connection closed, without any explicit unlock: if an instance crashes, the database notices the dead session and frees the lock. That last property is what a lease timeout tries to give other systems, and PostgreSQL gets it for free from the connection.

There is a transaction-scoped variant that releases at commit or rollback, which is easier to get right in application code because a forgotten unlock cannot happen.

Text
xact lock while A's transaction is open: B gets it = false
after A commits                       : B gets it = true
java
@Transactional
public boolean runIfLeader(Runnable job) {
    Boolean got = jdbc.queryForObject("select pg_try_advisory_xact_lock(?)", Boolean.class, 7L);
    if (Boolean.TRUE.equals(got)) {
        job.run();                       // the lock is held until this method's transaction ends
        return true;
    }
    return false;
}

Keep the job short, since the transaction, and the connection it uses, stay open for its duration. For a long job, take a session-level lock on a dedicated connection that you hold deliberately, and release it in a finally.

Pooling traps with session locks

A session-level advisory lock belongs to the connection, not to your code. With a connection pool, pg_advisory_lock on one borrowed connection and pg_advisory_unlock on another leaves the lock held by the first connection after it returns to the pool, where a later, unrelated request inherits it. If you use session locks, borrow one connection, lock, work, unlock and return it in the same block. Transaction-scoped locks avoid the issue entirely, and PgBouncer in transaction pooling mode supports only those.

What the lock does not give you

A lock tells you who may start. It does not make the protected work safe if the holder pauses and loses the lock. A process paused by a long garbage collection, or cut off by a network partition, can wake up believing it still holds the lock while another instance has taken over. The defence is a fencing token: a number that increases with each acquisition, passed to the resource, which rejects any write with a token older than one it has seen.

SQL
UPDATE jobs SET state = :state, fence = :fence
WHERE id = :id AND fence < :fence;          -- a stale holder's write changes nothing

If the work is idempotent, the simpler answer is to allow both instances to run it and make the second one a no-op. Choose a lock for efficiency, so that the same work is not done twice, and fencing or idempotency for correctness. A Redis SET key value NX PX 30000 lock fits the first purpose, and relies on the clock and the lease for the second, which is why the cases where two holders is harmful should not rely on it.

Scheduled jobs: use a lock designed for them

The most common reason to want a distributed lock is a scheduled job that must run on one instance of a service that has several. For that case, do not write the lock yourself. ShedLock wraps a scheduled method with a lock held in a table (or Redis, or another store) and handles the expiry and the cleanup.

java
@Scheduled(cron = "0 */5 * * * *")
@SchedulerLock(name = "settle-payments", lockAtMostFor = "4m", lockAtLeastFor = "30s")
public void settlePayments() {
    settlement.run();
}

lockAtMostFor is the safety net: if the instance dies while holding the lock, others can take over after four minutes, so set it longer than the job's worst realistic duration. lockAtLeastFor prevents two instances with slightly different clocks from both running the same tick. If the job can exceed lockAtMostFor, extend the lock while working or the job will overlap itself, which is the failure to test for. A table with a unique name column and an UPDATE ... WHERE lock_until < now() is all the library needs, so it adds one table to a service that already has a database.

Where this does not apply

For single-instance applications, use an ordinary ReentrantLock. The reasoning is in How to do distributed locking and the Redis lock documentation.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.