Isolation level
Fisrt, befor understand the Lock, we shouldl know the what is the Isolation level.
Transaction isolation level means how much transactions are isolated each other, while we process various transactions at the same time. It can decide the standard which Applicable transaction is able to read the changed data from another tractions.
Four kind of the Isolation level
The higher the transaction isolation level, the more resources are used and the performance deteriorates. In general, use either READ COMMITTED or REPEATABLE READ.
What is the Perssimistic Lock?
What is the Optimistic Lock?
Pessimistic locking can be done using the @Lock annotation in SpringDataJPA.
public interface UserRepository extends JpaRepository<User, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select b from User b where b.id = :id")
User findByIdForUpdate(Long id);
}
Additionally, if you are using Row JPA, you can specify lock directly through EntityManager.
entityManager.lock(user, LockModeType.OPTIMISTIC);
The types of LockModType that implement pessimistic locking in JPA are as follows.
Pessimistic locking can degrade performance because it locks the retrieved record itself.
If performance issues are found, optimistic locking should be considered.
To use optimistic locking in SpringDataJPA, add @Version to entities.
@Entity
public class Board {
@Id
@GeneratedValue
private Long id;
@Version
private Long version;
}
Now whenever an entity is modified, since JPA itself supports versioning, an ObjectOptimisticLockingFailureException exception occurs if the search and modification times are different.
The types of LockModType that implement optimistic locking in JPA are as follows.
OPTIMISTIC
OPTIMISTIC_FORCE_INCREMENT
If you use JpaRepository, you can specify LockModeType of @Lock annotation.
@Lock(LockModeType.OPTIMISTIC)
Optional<User> findByIdForUpdate(Long id);
The @Lock of JPA Repository Method of @Transactional isolation level has the following difference.
Organize
The @Lock of JPA Repository Method of @Transactional isolation level has the following difference.
Optimistic locking generally outperforms pessimistic locking, which locks records from the moment a processing request is received until processing is complete.
Depending on the nature of the data, there are cases where pessimistic locks are good, and this is the case.
There is one product in stock. 1 million users concurrently request orders. In the case of a pessimistic lock, all but one user waits to determine whether a transaction conflicts in advance. In other words, you don't have to know in advance that there is no stock, and you don't have to do complicated processing.
In the case of an optimistic lock, the user who sent the simultaneous request processes them sequentially, and only when the user commits, it is recognized that there is no inventory. In addition, since rollback is required as much as processing has been performed, resource consumption is greatly increased.