Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of J2EE transaction concurrency control strategy

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this article, the editor introduces in detail "what are the knowledge points of J2EE transaction concurrency control strategy", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "what are the knowledge points of J2EE transaction concurrency control strategy" can help you solve your doubts.

Transaction concurrency access control strategy

In the current J2EE project, a common problem is that if we control the concurrent access of transactions, although some persistence layer frameworks have done a lot of work for us, understanding the principle is still very useful for our development.

Transaction concurrent access can be divided into two types, namely, the concurrent access control of the same system transaction and cross-transaction access, in which the same system transaction can adopt optimistic locking and pessimistic locking strategy. optimistic offline locking and pessimistic offline locking are needed for multiple system transactions. Before discussing these four concurrent access control strategies, we need to clarify the isolation level of database transactions. The ANSI standard specifies four isolation levels of database transactions, which are:

Read uncommitted (Read Uncommitted)

This is the transaction isolation level of *. Read transactions do not block read transactions and write transactions, and write transactions do not block read transactions, but block write transactions. One result of this is that when a write transaction is not committed, the read transaction can still be read, which results in dirty reading.

Read submitted (Read Committed)

With this isolation, write transactions block read transactions and write transactions, but read transactions do not block read transactions and write transactions, so that because write transactions block read transactions, read transactions cannot read dirty data, but because read transactions do not block other transactions, this still causes unrepeatable reading problems.

Repeatable read (Repeatable Read)

With this isolation level, read transactions block write transactions, but read transactions do not block read transactions, but write transactions block write and read transactions. Because the read transaction blocks the write transaction, it does not cause unrepeatable reading problems, but it still does not avoid phantom reading problems.

Serialization (serializable)

This isolation level is the strictest isolation level, and if it is set to this level, then all of the above problems will not occur (dirty reading, non-repeatable reading, phantom reading). But this will greatly affect the performance of our system, so we should avoid setting this isolation level, instead, we should adopt a lower isolation level. Then use concurrency control strategy to control the concurrency access of transactions.

In fact, we can also set the transaction isolation level to serializable, so that we do not need to adopt concurrency control strategy, and the database will do all concurrency control for us, but this will seriously affect the scalability and performance of our system, so in practice, we generally use read committed or lower transaction isolation level, with a variety of concurrent access control strategies to achieve the purpose of concurrent transaction control. Here is a summary of the common control strategies:

1 optimistic lock

Optimistic locking is a strategy that we often adopt in the same database transaction, because it enables our system to maintain high performance and improve good concurrency access control. Optimistic lock, as the name implies, is to maintain an optimistic attitude, we think that the transactions in the system will not be updated very frequently, even if there is a conflict, it will be fine, just do it all over again. The basic idea is that every time a transaction update is committed, we want to see if what we want to modify has been modified by another transaction since it was last read, and if so, the update will fail.

* We need to clarify a problem, because optimistic locks do not actually lock any records, so if the transaction isolation level of our database is set to read committed or lower isolation sectors, then the problem of unrepeatable reading can not be avoided (because reading transactions will not block other transactions at this time), so when using optimistic locking, the system should allow the problem of unrepeatable reading.

After understanding the concept of optimistic locking, how do we use this strategy in our system at present? Generally speaking, the following three methods can be used:

Version field: add a version control field to our entity and add 1. 1 to the value of the version field after each transaction update.

Timestamp (timestamps): after adopting this strategy, each time an update is committed, the current time of the system is compared with the time when the entity was loaded, and if it is inconsistent, an optimistic lock failure is reported, thus rolling back the transaction or retrying the commit. There are some disadvantages in using timestamps, for example, in a cluster environment, the time synchronization of each node may be a problem, and if the interval between concurrent transactions is less than the smallest clock unit of the current platform, then there will be a problem of overwriting the result of the previous transaction. Therefore, it is generally better to use the version field.

Detection based on all attributes: when using this strategy, you need to compare whether each field has been modified after reading, so it is troublesome to implement this strategy, requiring that each attribute be compared. If hiernate is used, because Hibernate can detect dirt in the first-level cache, then you can determine which fields have been modified and dynamically generate sql statements for update.

Here's a summary of how to use optimistic locks in JDBC and Hibernate:

Optimistic locking is used in JDBC: if we use JDBC to implement the persistence layer, we can adopt the above three strategies that support optimistic locking, add a version field or a Date field to the entity, or adopt a policy based on all attributes. Here is a demonstration using the version field:

If there is an entity class of Account in the system, and we add an extra version field to the Account, then our JDBC Sql statement will read as follows:

Select a.version....from Account as a where (where condition..)

Update Account set version = version+1. (another field) where version =? (another contidition)

In this way, we can judge by the number of rows of the update result. If the number of rows of the update result is 0, then the entity has been changed by other transactions since it was loaded, so a custom optimistic locking exception is thrown (or you can use the exception system encapsulated by Spring). Specific examples are as follows:

.

Int rowsUpdated = statement.executeUpdate (sql)

If (rowsUpdated= = 0) {

Throws new OptimisticLockingFailureException ()

}

.

In the case of using JDBC API, we need to update and judge the version field in each update statement, so if we are not careful, there will be a problem that the version field is not updated, on the contrary, the current ORM framework has done everything for us, all we need to do is to add version or Date fields to each entity.

Optimistic locking is used in Hibernate: if we use Hibernate as the persistence layer framework, it will be very easy to implement optimistic locking, because the framework will help us generate corresponding sql statements, which not only reduces the burden on developers, but also is not error-prone. The following is also summed up in the version field:

Similarly, if there is an entity class of Account in the system, we add an extra version field to the Account.

Public class Account {

Long id

.

@ Version / / can also be configured with a XML file

Int version

.

}

In this way, every time we commit a transaction, a corresponding SQL statement will be generated inside the hibernate to increase the version field by 1, and the corresponding version will be checked. If a concurrent optimistic lock exception is detected, then StaleObjectStateException.

2 pessimistic lock

The so-called pessimistic lock, as the name implies, is to adopt a pessimistic attitude towards transaction concurrency. We think that concurrent updates in the system will be very frequent, and it will cost a lot of money to start all over again after the transaction has failed. We need to use a real lock to implement it. The basic idea of pessimistic locking is that every time a transaction reads a record, it will be locked, so that other transactions must wait for the previous transaction to commit or roll back to unlock.

* We still need to make it clear that if the isolation level of our database transaction is set to read committed or lower, then through pessimistic locking, we control the problem of unrepeatable reading, but can not avoid the problem of phantom reading (because to avoid it, we need to set the database isolation level to Serializable, and generally we will take read committed or lower isolation level. And cooperate with optimistic or pessimistic locks to achieve concurrency control, so phantom reading problems can not be avoided. If you want to avoid phantom reading problems, you can only rely on the serializable isolation level of the database (fortunately, phantom reading problems are generally not serious).

Let's summarize it in terms of JDBC and Hibernate, respectively:

Use pessimistic lock in JDBC: to use pessimistic lock in JDBC, you need to use select for update statement. If we have a class of Account in our system, we can do it in the following way:

Select * from Account where... (where condition).. For update.

After using the for update statement, each time a record is read or loaded, the loaded record is locked, so when other transactions update or load the record, it will be blocked because the lock cannot be obtained, thus avoiding the problem of unrepeatable and dirty reading, but other transactions can still insert and delete records. Maybe two reads in the same transaction will get different result sets, but this is not a problem caused by pessimistic locking, it is a problem caused by our database isolation level.

* it is also important to note that in every conflicting transaction, we must use select for update statements to access the database. If some transactions do not use select for update statements, it is easy to cause errors, which is also the disadvantage of using JDBC for pessimistic control.

Use pessimistic locks in Hibernate: it will be much easier to use pessimistic locks in Hibernate than in JDBC, because Hibernate has API for us to call, thus avoiding writing SQL statements directly. Here's a summary of Hibernate's use of pessimistic locks:

First of all, it is necessary to clarify the two modes that support pessimistic locks in Hibernate: LockMode.UPGRADE to LockMode.UPGRADE_NO_WAIT. (PS: in JPA, the corresponding lock mode is LockModeType.Read, which is different from Hibernate.)

If we have an Account class in our system, the specific operation can be like this:

.

Session.lock (account, LockMode.UPGRADE)

.

Alternatively, you can load the object as follows:

Session.get (Account.class,identity,LockMode.UPGRADE).

In this way, when the object is loaded, the corresponding select for update statement will be generated inside the hibernate to load the object, thus locking the corresponding record and avoiding concurrent updates from other transactions.

After reading this, the article "what are the knowledge points of J2EE transaction concurrency control strategy" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it before you can understand it. If you want to know more about related articles, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report