Locks
A lock gives one holder at a time the right to do some work, for a bounded time (the lease). Holders can lose a lock without knowing it (a pause, a network split, an expired lease), so every lease carries a fencing token: a number that grows with each acquisition. Whatever the protected work writes to should reject a write carrying a lower token than one it has already seen. The lock alone cannot make that guarantee; the token is what lets the resource make it.
The same lock rules and the same database statements and Redis scripts are used by both languages
(conformance/sql/locks, conformance/lua/locks, compared byte for byte), so a Java replica and a Go
replica exclude each other on one database or one Redis server.
Setting up
Section titled “Setting up”Lock stores are named in code, each with the driver its factory chooses; there is no locks
configuration (an application can have many lock stores, so they are code, see Configuration or
code). The database and Redis instances they use are
configuration. All three drivers, as in the locks-demo example:
App.builder() // the database and Redis instances, pools included, are configuration .module(new DatabaseModule()) .module(new RedisModule()) // lock stores can be many, so they are code: one per driver, the driver chosen here .module( LocksModule.builder() .store("main", DatabaseLockStores.database()) .store("shared", RedisLockStores.redis("default", "fw:lock:")) .store("local", LockStores.memory()) .defaultStore("main") .build()) // the fw_lock migration the database store needs .module(new LocksDatabaseModule());| Factory | Driver | Needs |
|---|---|---|
LockStores.memory() (framework-locks) |
memory: one JVM only |
nothing |
DatabaseLockStores.database(), database(instance) (framework-locks-database) |
database on the default (or a named) database instance |
DatabaseModule, and LocksDatabaseModule for the fw_lock migration; on another instance the table must exist, start-up checks |
RedisLockStores.redis(), redis(connection), redis(connection, prefix) (framework-locks-redis) |
redis on the default (or a named) connection, keys under fw:lock: (or your prefix: not blank, at most 100 characters) |
RedisModule |
app.get(Locks.class) is the registry: get(name), defaultInstance(), names(). A factory is a
LockStoreFactory (create(name, lookup)), so you can write your own and read your own settings from
the lookup’s Config.
d := declared{locks: locks.Declare(app)}dblock.Declare(app) // the fw_lock migrationall, err := locks.Build(ctx, b, d.locks, locks.WithStore("main", dblock.Store(dbs)), locks.WithStore("shared", redislock.Store(clients, redislock.Connection("default"), redislock.Prefix("fw:lock:"))), locks.WithStore("local", locks.Memory()), locks.DefaultStore("main"))The drivers are packages compiled only when imported: the memory driver in locks, locks/dblock
(PostgreSQL) and locks/redislock (Redis). The Redis prefix defaults to fw:lock:, is not blank and
has at most 100 characters. dblock.Declare also contributes the lock table’s migration set (the Java
file byte for byte). A database instance other than the default is checked for fw_lock at start-up.
Store names match [a-z][a-z0-9-]* and are unique. With one store it is the default; with several, you
must name the default or start-up fails. A leftover locks section in a file fails start-up with the
code to write instead.
Taking a lock
Section titled “Taking a lock”The usual call acquires, runs your action while the lease is refreshed every third of its length, and releases.
LockStore store = app.get(Locks.class).defaultInstance();WithLockResult<String> result = store.withLock( LockKey.service("nightly-export"), Duration.ofSeconds(30), // lease length Duration.ZERO, // how long to wait for the lock lease -> "fence " + lease.fencingToken());return switch (result) { case WithLockResult.Completed<String> c -> c.value(); case WithLockResult.NotAcquired<String> n -> "someone else has it"; case WithLockResult.Lost<String> l -> "lost the lock";};A virtual thread refreshes the lease. LockedAction<T> is T run(Lease lease) throws Exception; the
action receives the lease so it can pass lease.fencingToken() to what it writes. Results are sealed
types: handle them with an exhaustive switch. An exception from the action is rethrown after the lock
is released: unchecked ones unchanged, checked ones wrapped in LockedActionException.
res, err := locks.With(ctx, lock, key, 10*time.Second, 5*time.Second, func(_ context.Context, lease locks.Lease) (string, error) { return fmt.Sprintf("token %d", lease.Fence()), nil })With acquires (retrying with backoff until maxWait), runs the action, refreshes the lease every
lease / 3, and releases it afterwards. The action’s context is cancelled when the lease is lost;
the result’s Outcome is Completed, NotAcquired or Lost. An error from the action is returned
beside the outcome; the context error caused by a loss is not. An action that ignores its context keeps
running, as a Java thread that ignores interrupts does.
| Result | Meaning |
|---|---|
| Completed (value) | the action returned and the lock was held throughout |
| NotAcquired | the lock was busy for the whole wait; the action did not run |
| Lost | the lock was lost while the action ran (a refresh found it taken or expired, or kept failing past the lease). The action was interrupted or its context cancelled. A value is present if the action still returned normally. Treat the work as having run without exclusion. |
The lower-level operations
Section titled “The lower-level operations”LockStore has tryAcquire(key, lease) (Acquired(Lease) or Busy), acquire(key, lease, maxWait)
(retries with backoff, 10 ms doubling to 250 ms with jitter), refresh(lease, newLease) (Refreshed or
Lost) and release(lease) (Released or NotHeld). Lease has key(), ownerToken(),
fencingToken(), remaining() and expiredLocally(); its local deadline is computed from the holder’s
monotonic clock reading taken before the request, so it is never later than the store’s own expiry.
Lock.TryAcquire and Lock.Acquire return an Acquisition (Acquired with the Lease, or Busy);
Refresh returns the refreshed lease and whether it was still held; Release whether it was.
locks.NewGate and locks.ServiceGate (Java: LockGate.of and LockGate.service) gate a background loop: a run happens only on the holder of the
lock (no wait), with the fencing token in its tick.
Lease lengths run from 100 ms to 24 h and the maximum wait from zero to 24 h; outside that is an
argument error (IllegalArgumentException, ErrInvalidArgument). Passing a lease from one store to
another is also an argument error. Infrastructure failure (store unreachable, query error) is
LockStoreUnavailableException in Java and wraps ErrStoreUnavailable in Go. Not being able to get the
lock is never an exception.
| Scope | Java | Go | Stored form |
|---|---|---|---|
| service | LockKey.service("nightly-export") |
locks.ServiceKey("nightly-export") |
svc:nightly-export |
| client | LockKey.client(clientId, "invoice-run") |
locks.ClientKey(client, "invoice-run") |
client:<clientId>:invoice-run |
Names match [A-Za-z0-9._:-]{1,200}. A client-scoped key can never equal a service-scoped one, and two
clients never collide.
Guarantees and the differences between drivers
Section titled “Guarantees and the differences between drivers”Every driver guarantees: at most one unexpired lease per key on the store’s clock; fencing tokens
that strictly increase per key (not consecutive); refresh and release act only for the current owner
and only before expiry; locks are not reentrant (acquiring a key you hold is busy); and release is
immediate.
| Driver | Use it for | Caveat |
|---|---|---|
memory |
one process: development and tests | two processes do not exclude each other |
database |
the default choice in production; uses the default or a named PostgreSQL instance and its clock | needs the fw_lock table; on a non-default instance the driver checks at boot that it exists and fails start-up otherwise (migrations do not run there) |
redis |
a single Redis or Valkey server | not Redlock. If the server loses data (a failover to a replica that missed writes, a restart without persistence), a lock can be held twice and fencing tokens can repeat. If you need more, use database |
Testing
Section titled “Testing”MemoryLockDriver takes a clock supplier, so a test can move time without sleeping. The
framework-locks test-jar publishes LockStoreContract, an abstract JUnit class every driver’s test
extends, and AdjustableClock. Tests of your own code can configure a memory store and use
builder.monotonicClock(...).
lockstest.Run(t, harness) is the contract’s suite, one subtest per case (50 racing acquirers,
increasing tokens over release and expiry cycles, refresh, loss after expiry, stale release, not
reentrant, waiting, key scopes, With refreshing, losing and releasing, argument limits). Every
driver’s tests call it:
lockstest.Run(t, lockstest.Harness{New: func(t *testing.T) lockstest.Env { clock := &lockstest.OffsetClock{} store := locks.NewMemoryStore(clock) return lockstest.Env{ Lock: locks.New(store, locks.WithClock(clock)), Expire: func(_ *testing.T, k locks.Key) { store.ExpireNow(k.Stored()) }, Pass: func(_ *testing.T, d time.Duration) { clock.Advance(d) }, }}})See Testing.
Not built
Section titled “Not built”There is no purge job for idle fw_lock rows (tokens come from one sequence, so rows could be deleted
later without breaking the guarantees). Wrapper drivers (failover, metered) are not implemented.
Specification: Locks.