# Lock

Mongock uses a pessimistic lock to synchronise multiple Mongock instances accessing to the same database.

# Overview

Although this is completely configurable, the default, expected and recommended behaviour is Mongock acquiring the lock before starting the migration, trying up to certain number of times(if it's already taken or there is any connection issue). Once taken, it will "reserve" it initially for some time(lockAcquiredForMinutes). Then Mongock will ensure the lock is acquired in every access to the database. When the time for which the lock was acquired is near to expire, Mongock will extend it using the same amount of minutes(lockAcquiredForMinutes). This process will be repeatedly performed until the migration is finished in order to ensure the lock is acquired until the end of the migration.

# What happens if the lock is acquired for a shorter period than the migration and cannot be re-acquired?

This is very unlike as the only instance allowed to update the lock collection is the one in possession of the lock, but it's technically possible to experiment connection issues when refreshing the lock. When this happens, the lock is implicitly released(or about to) because it is expired, so the current migration is aborted and any other Mongock instance can acquire it. The result of the migration will depend on wether the migration is transactionable or provides recovery process.

# How is the lock ensured in every database access?

Mongock uses two mechanisms for this. Static and dynamic lock guardian.

MongockTemplate must be used instead of MongoTemplate.


Custom beans in changeSet methods must be interfaces.


# Configuration

There are just 4 parameters to tune the lock.You can configure them by using properties or builder. Please see the runner configuration section for more information.


When using the builder method setLockConfig, which takes lockAcquiredForMinutes, maxWaitingForLockMinutes and maxTries as parameters, will implicitly set throwExceptionIfCannotObtainLock to true.

However, in common scenarios it doesn't makes much sense, but you can set it to false afterwards with method throwExceptionIfCannotObtainLock though.