Class LeaderElectionWorker

java.lang.Object
com.axelor.app.leader.LeaderElectionWorker

public class LeaderElectionWorker extends Object
The LeaderElectionWorker class is responsible for managing a leader election mechanism among multiple instances of a distributed system. This class ensures that only one node acts as the leader at a time using PostgreSQL Session-Level Advisory Lock.

The class uses a scheduled task to periodically attempt to acquire leadership or verify the continued validity of the leader's lock. It operates on a single background thread to manage the election process.

Only available on PostgreSQL databases

  • Method Details

    • getInstance

      public static LeaderElectionWorker getInstance()
      Retrieves the singleton instance of the LeaderElectionWorker.
      Returns:
      the single instance of the LeaderElectionWorker.
    • stop

      public void stop()
      Stops the leader election service gracefully.

      This shuts down the scheduler, interrupts any running thread, and closes the database connection (releasing the lock).

    • start

      public void start()
      Starts the background leader election service.

      This initializes a single-thread scheduler with a Daemon thread. The election process runs immediately (0 delay) and repeats every 300 seconds.

    • isLeader

      public boolean isLeader()
      Indicates whether the current instance is the leader.
      Returns:
      true if the current instance holds leadership, false otherwise.
    • isRunning

      protected boolean isRunning()
      Checks if the election service is currently active.
      Returns:
      true if the scheduler is running.