How to fix liquibase.exception.LockException: Could not acquire change log lock

This tutorial addresses the Liquibase Lock exception encountered during server startup.

Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Caused by: liquibase.exception.LockException: Could not acquire change log lock. Currently locked by
Liquibase Update Failed: Could not acquire change log lock.  Currently locked by S

This error occurs when running database migration or batch scripts while the database is locked for updates.

First, let’s understand the Liquibase Lock mechanism.

How does Liquibase Lock work?

Liquibase offers lock services to maintain concurrency during multiple threads attempting to update/modify the database. It ensures that only one thread modifies the database at any given time using locking mechanisms.

By default, Liquibase saves changelog script changes in the DATABASECHANGELOGLOCK table. Applications configured to run database migration scripts execute them during startup.

During startup, Liquibase performs the following actions

  • It acquires the lock and locks the database, creating the databasechangeloglock table and adding a record to it. Once the lock is acquired, only one thread can modify the database state. The databasechangeloglock table contains a locked column with a value of true.
  • It then runs the scripts configured in changelogs.
  • After successful script execution, it releases the locks by updating the databasechangeloglock table’s locked column to false.
  • The Could not acquire change log lock issue occurs if your application deployment is halted once the lock is acquired, as the lock remains available and is not released.

Now, let’s discuss how to resolve this error.

How to fix the Liquibase Lock error

Since the database is still locked, it needs to release the lock to run the database scripts.

There are multiple ways to resolve the issue:

  • First method: remove database lock tables

    • Stop the application.

    • Connect to the database and remove the databasechangelog and databasechangelog.lock tables.

      TRUNCATE TABLE DATABASECHANGELOGLOCK
      
      or
      drop table  DATABASECHANGELOGLOCK
      or
      delete from   DATABASECHANGELOGLOCK
      
    • Restart the application

  • Second method: update the locked column value to zero

select * from DATABASECHANGELOGLOCK;

This will output a record indicating that the database is locked, with Locked > 0.

Find the id and update the record with the given id using the following command.

update DATABASECHANGELOGLOCK
set locked=0, lockgranted=null, lockedby=null
where id=value

Note: Locked = 0 may vary based on the database; it can be FALSE or f.