About locks and transactions

I mentioned volatile before, and then I saw synchronize when I checked the information. I suddenly remembered that this thing was added directly to the service layer by colleagues, but it didn't seem to be completely reliable.

Because the simple distributed lock redission has been used before , and then redission is a lock in the service layer method , the result is that the database data is still inconsistent (that is, the lock is not useful).

The call is as follows:

(1)req -> (2)web.method -> (3)service.method (open transaction) -> (4)redission lock (lock) -> (5)execute business -> (6)redission unlock( Release lock) -> (7) End of method (transaction commit) -> (8) Return data;

Everything looks so beautiful, the whole process is done in one go. But why is there no use for eggs? ?

The reason is: in the case of a large amount of concurrency, a large number of threads are blocked in (3) -> (4) When a thread releases the lock but does not commit the transaction (ie (6) -> (7)) , another thread instantly acquires When it comes to the lock, the lock becomes a decoration, and there is a problem with the natural data.

As for synchronize, although I haven't used it much, I personally feel that this kind of problem also occurs. Although synchronize is added to the method, the transaction is at the AOP level. It will be opened before the method is entered, and the method will not be submitted until the end of the method.

So I usually simply lock the web layer. .

Speaking of this, I also briefly summarize the handling of simple concurrency :

1. Pessimistic way: that is, lock each time, such as redission (distributed lock),  ReentrantLock (single application), etc.

2. Optimistic way: 1 Use the version number version, but need to add fields to the data table;

                         2 Modify the data first, then query the data, and make a judgment (usually check first and then change); 

Pessimistic way: may cause a large number of threads to hang, interface congestion, and access denied.

Optimistic way: Every time you access the database, the pressure on the database increases, especially when a large number of rollback operations occur, the database may stop working.

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_36338555/article/details/103728147