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

    Fields
    Modifier and Type
    Field
    Description
    static final int
    Default acquisition timeout, in seconds.
  • Method Summary

    Modifier and Type
    Method
    Description
    default boolean
    acquireLock(String lockName)
    Attempts to acquire the named lock using DEFAULT_TIMEOUT_SECONDS.
    boolean
    acquireLock(String lockName, int timeoutSeconds)
    Attempts to acquire the named lock within the specified timeout.
    boolean
    releaseLock(String lockName)
    Releases one acquisition of the named lock on the session's connection.
  • Field Details

  • Method Details

    • acquireLock

      default boolean acquireLock(String lockName)
      Attempts to acquire the named lock using DEFAULT_TIMEOUT_SECONDS.
      Parameters:
      lockName - the name of the lock
      Returns:
      true only when the lock was acquired
    • acquireLock

      boolean acquireLock(String lockName, int timeoutSeconds)
      Attempts to acquire the named lock within the specified timeout.
      Parameters:
      lockName - the name of the lock
      timeoutSeconds - 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

      boolean releaseLock(String lockName)
      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.