jpa lock

basis

You first need to understand a few basic concepts, critical update locks to avoid conflicts caused by two concurrent users simultaneously update the same data caused.

  • Concurrency: The system can simultaneously handle many requests in parallel;
  • Synchronous and asynchronous: synchronization refers to a service refers to doing one thing; doing asynchronous is a one, need not always wait for the results, you can do other things, until there is a result, to continue in its business; when in sync for certain data, it can be operated directly;
  • Dirty: dirty read refers to when a transaction is accessing data, and the data has been modified, and this modification has not been submitted to the database, then, another transaction also access the data, and then use this data. Because this data is not submitted, then another transaction read this data is dirty data (Dirty Data), according to data made dirty operation may be incorrect.
  • Non-repeatable read: non-repeatable read means within a transaction, reading the same data multiple times. When this transaction is not over, another transaction also access the same data. So, between the two read data in the first transaction, due to the modification of the second transaction, then the first transaction data may be read twice is not the same. This occurs in a transaction the two read data are not the same, so called non-repeatable read

Using locks scene
plurality of the same service (distributed environment) may also operate on a particular data / plurality of transactions, while other operations additions and changes deleted;

Lock Introduction

One is, as java synchronization locks on the code level, typical is synchronized keyword synchronized, and here I do not do too much to explain.
Another is to compare typical is optimistic and pessimistic locking lock on the database level. Here we focus on explaining is pessimistic locking (traditional physical locks) and optimistic locking.

Pessimistic locking

As the name implies, it refers to the data by outsiders (including the current affairs of the other systems, and transaction processing from external systems) to modify a conservative approach, therefore, the entire data processing, the data is locked.

Implement pessimistic locking, often rely lock mechanism provided by the database (the database layer, only lock mechanism provided in order to truly ensure exclusive access to the data, otherwise, to achieve a locking mechanism even in this system, there is no guarantee does not modify the external system data).
A typical dependency pessimistic locking database call:

 select * from account where name=”Erica” for update 

This sql statement to lock all records matching your search criteria (name = "Erica") in the account table.
Prior to this transaction commits (release locks during a transaction when the transaction commits), the outside world can not modify these records.

Optimistic locking

For relatively pessimistic locking, optimistic locking mechanism taken a more relaxed locking mechanism. Rely on the database lock mechanism to achieve pessimistic locking in most cases, in order to ensure the greatest degree of exclusivity operation. But the attendant is significant overhead database performance, especially for long transaction, which often can not afford the overhead. Such as a financial system, and when an operator reads the user's data, read and modify user data base (such as changing the user account balance), if pessimistic locking mechanism, which means that the whole operation in (read data from the operator to start the whole process until commit changes modify the results, even including the time the operator goes to the brewed coffee), a database record is always in the locked state, one can imagine that if the face of hundreds of thousands concurrent, such a situation would lead to what the consequences.
Optimistic locking mechanism to some extent solved the problem. Optimistic locking, most of the data version (Version) recording mechanism implementation.

update xxx,version+1  where xxxx and version=x 

What version of the data? A version identifier data is the increase in the release solution is based on a database table, is generally achieved by adding a "version" database table fields. When reading out the data, read together this version, when after the update, this version number plus one. At this time, the data will be submitted to the version with the current version of the database table data corresponding to the information recorded for comparison, data submitted is greater than the version number of the database table if the current version number, the update them, or that the data is expired.

Examples of modifications books

  • Suppose the account information in the database table has a version field, a current value of 1; field and the current account balance (Balance) of 100.  At this time, the operator A to read out (version = 1), and deducted from the account balance50.
  • During operation of the operator A, the operator B also reads the user information (version = 1), $ 20 and deducted from the account balance.
  • The operator A complete revision of the data version number plus one (version = 2), together with the account deductions balance (balance = $ 50), committed to the database update, this time due to submit data version is greater than the database records the current version of the data is updated database record is updated to version 2.
  • The operator B to complete the operation, but also the version number plus one (version = 2) try to submit data (balance = $ 80) to the database, but this time than the discovery of the database record version, data version number of the operator B, filed 2 , the database also records the current version 2, does not meet the "submit version must be greater than the current version of the record in order to perform the update," the optimistic locking strategy, therefore, the operator B submission was rejected. Thus, to avoid the operator B with the cover of the operation result of operator A may be based on the old version = 1 modified data results. As can be seen from the above example, the long optimistic locking mechanism avoids the overhead of locking the transaction database (process operator A and operator B operation, the data of the database are not locked), greatly enhance the large amount of concurrency overall system performance.

Note that: optimistic locking mechanisms are often based on data stored in the logic system, and therefore also have certain limitations, such as in the embodiment, since the optimistic locking mechanism is implemented in our system, the user updates the balance from an external system uncontrolled operation of our system, it may
cause dirty data is updated in the database. In the system design stage, we should fully take into account the possibility of these situations occur, and adjust accordingly (such as the optimistic locking strategy implemented in the database stored procedure, based on the data available only outside this stored procedure update paths, rather than the database table directly open to the public).

JPA basis

JPA built optimistic locking achieved in its data access engine. If you do not consider the external system update operation of the database, using the transparency optimistic locking JPA implementation provided, will greatly enhance our productivity.
Update JPA in order to ensure the process object will not be modified outside world, will save automatically lock the target object plus WRITE method implementation.

Optimistic locking achieve

Well, he said so long lock of basic concepts and knowledge, we look at how to implement data locks operated by JPA.

In JPA, @ Version annotation, you can achieve optimistic locking function

Entity class User, add annotations on the version attribute @Version

import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Version; import java.math.BigDecimal; @Entity public class Student{ @Id private int id; private String name; private BigDecimal money; @Version private int version; // getters and setters } 

Lock mode

We offer two different JPA optimistic lock modes (and two aliases):

  • OPTIMISTIC / READ - version contains all the attributes of an entity to obtain optimistic read lock
  • OPTIMISTIC_FORCE_INCREMENT / WRITE - and obtained as OPTIMISTIC lock and automatically increase the value of the version attribute of
    all the above types of LockModeType complete definition.

OPTIMISTIC (READ)
We know OPTIMISTIC lock and Read, the two are synonymous. But JPA specification recommends OPTIMISTIC we use in new applications. Whenever we request OPTIMISTIC mode, always check the version when the transaction commits, so optimistic locking to ensure repeatable read.
Simply put, it should ensure that any transaction can not be submitted in the following cases:

  • It has been updated or deleted but did not submit
  • At the same time we have been successfully updated or deleted

OPTIMISTIC_INCREMENT (WRITE)
As before, OPTIMISTIC_INCREMENT and WRITE are synonymous, but the former is more preferable. OPTIMISTIC_INCREMENT OPTIMISTIC mode must satisfy the same conditions. However, it does not specify whether it should be done immediately, or whether it should be deferred to submit or refresh. Always the cumulative physical version (even if the entity does not change at this time) and the version check when the transaction commits, so optimistic locking to ensure repeatable read.

JPA lock type

  • LockModeType.OPTIMISTIC_FORCE_INCREMENT: optimistic locking, the default lock type.

  • LockModeType.OPTIMISTIC_FORCE_INCREMENT: with another entity to lock the reference to the current entity, we need to use it. When the transaction is committed, even if there is no change in the state of affairs of the entity, the entity version of the column will increase.

Example: Suppose we have two entities "book (Book)" and "bookshelf (Shelf)". We can add the book to your library, but the book does not hold a reference to its shelves. We need to lock action bookshelves of books for all mobile, in order to avoid a book is placed on two shelves. To lock this action, light shelves to lock the current entity is not enough, because the book may not have put on a shelf. Lock all shelves and unreasonable, because they may have been different in different affairs. The book is only reasonable to lock the entity itself, and it has not changed even in our case (because it does not hold its reference bookshelf).

  • LockModeType.PESSIMISTIC_READ: pessimistic locking. Entity other transactions can be read simultaneously, but can not update it at the same time.

  • LockModeType.PESSIMISTIC_WRITE: pessimistic locking. LockModeType.PESSIMISTIC_READ is an enhanced version. Other transactions can not read or write entity simultaneously.
    Note: OpenJPA distinguish PESSIMISTIC_READ and PESSIMISTIC_WRITE lock mode only for DB2 databases. In the run with other databases, there is no difference between the two modes, because PESSIMISTIC_READ lock mode has been upgraded to PESSIMISTIC_WRITE.

  • LockModeType.PESSIMISTIC_FORCE_INCREMENT: pessimistic locking. Other transactions can not read or write entity simultaneously. When the transaction is committed, even if there is no change in the state of affairs of the entity, the entity version of the column will increase. It is a combination of optimistic and pessimistic locking lock.

Use optimistic locking

Has a version property of the entity, optimistic lock by default are valid right. But there are several other ways to display specified:

Find
as parameters, may be obtained by passing the optimistic locking LockModeType to find a suitable method of EntityManager:

entityManager.find(Student.class, studentId, LockModeType.OPTIMISTIC); 

Query
Another method is a method by SetLockMode Query objects:

Query query = entityManager.createQuery("from Student where id = :id");
query.setParameter("id", studentId);
query.setLockMode(LockModeType.OPTIMISTIC_INCREMENT);
query.getResultList();

Displays the lock
display the specified lock by lock method invocation of EntityManager:

Student student = entityManager.find(Student.class, id); entityManager.lock(student, LockModeType.OPTIMISTIC); 

Refresh
As before, you can also call refresh ways:

Student student = entityManager.find(Student.class, id); entityManager.refresh(student, LockModeType.READ); 

NamedQuery
last use lockMode property @NamedQuery annotation:

@NamedQuery(name="optimisticLock",
query="SELECT s FROM Student s WHERE s.id LIKE :id", lockMode = WRITE) 

version attribute

In the optimistic-lock version attribute has the following optional values:

  • none: no optimistic lock
  • version: Version achieve through optimistic locking mechanism
  • dirty: optimistic locking achieved by checking the property changes had occurred
  • all: to achieve optimistic locking by examining all properties

So far, JPA and lock concepts and complete description, if there is a clear description of the place, please correct me!



Author: witty small Alone
link: https: //www.jianshu.com/p/dc954e09360d
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/vana/p/12104085.html