Interface DatabaseMutex
- All Known Implementing Classes:
DatabaseMySqlMutex,DatabasePostgresMutex
public interface DatabaseMutex
A named, connection-scoped database mutex.
Locks use the injected Session's connection. Always release in a finally block after successful acquisition, within the same session; committing or rolling back does not release the lock. Repeated acquisition by the same database session succeeds and must be matched by an equal number of releases; these locks do not exclude other callers sharing that database session.
Inject the generic interface to select the implementation for the session's database flavor, then run protected work only after successful acquisition:
@Inject
DatabaseMutex databaseMutex;
public void performProtectedWork() {
if(databaseMutex.acquireLock("lockName")) {
try {
// Protected work
} finally {
if(!databaseMutex.releaseLock("lockName")) {
// Handle an unsuccessful release.
}
}
} else {
// Lock was not acquired; skip or retry the work.
}
}
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intDefault acquisition timeout, in seconds. -
Method Summary
Modifier and TypeMethodDescriptiondefault booleanacquireLock(String lockName) Attempts to acquire the named lock usingDEFAULT_TIMEOUT_SECONDS.booleanacquireLock(String lockName, int timeoutSeconds) Attempts to acquire the named lock within the specified timeout.booleanreleaseLock(String lockName) Releases one acquisition of the named lock on the session's connection.
-
Field Details
-
DEFAULT_TIMEOUT_SECONDS
Default acquisition timeout, in seconds.- See Also:
-
-
Method Details
-
acquireLock
Attempts to acquire the named lock usingDEFAULT_TIMEOUT_SECONDS.- Parameters:
lockName- the name of the lock- Returns:
- true only when the lock was acquired
-
acquireLock
Attempts to acquire the named lock within the specified timeout.- Parameters:
lockName- the name of the locktimeoutSeconds- zero to try once, positive to wait up to that many seconds, or negative to wait indefinitely- Returns:
- true only when the lock was acquired; false on timeout or a null database result. Postgres also returns false when interrupted, preserving the interrupt flag. SQL execution errors propagate to the caller.
-
releaseLock
Releases one acquisition of the named lock on the session's connection.- Parameters:
lockName- the name of the lock- Returns:
- true only when the database confirms release; false when the lock is not owned by this session, does not exist, or the result is null. SQL execution errors propagate to the caller.
-