Discussion on locking table in concurrency situation

Source: Internet
Author: User

The share of the previous Friday, mainly for the project encountered some problems in the technical discussion, the following is a discussion on the database lock problem. The sample code uses JPA.

Situation: Station ticketing system, from A to B, but also the remaining 5 tickets. There are 30 users who purchase tickets at the same time, how to solve the concurrency problem through database lock.

Create a new T_ticket table, deposit a record, start with a, destination B, remaining ticket 5, data records such as:

First, suppose that we do not perform concurrency control and follow the general logic of processing. Open 30 threads to impersonate the user, query out the database records according to the origin, the destination, get the value of the Amount field, if it is greater than 0, then amount the field 1, then update to the database.

The code is as follows:

Executorservice ThreadPool = executors.newfixedthreadpool (int i = 0; i <; i++) {    Threadpool.execute (new Runnable () {public         void run () {               ticketservice.buyticket ("A", "B");         }    }); Threadpool.shutdown ();

Buyticket Method:

public void Buyticket (string origin, string destination) {Ticket Ticket = Ticketdao.getticket (origin, destination); ticket!=null) {int amount = Ticket.getamount (); if (amount>0) {Ticketdao.updateticketamount (Ticket.getid (), AMOUNT-1); System.out.println ("Successful purchase of tickets from" +origin+ "to" +destination+ ");} ELSE{SYSTEM.OUT.PRINTLN ("Ticket sold OUT!");}} Else{system.out.println ("No This shift!");}}

Execution thread, view output:

Buy tickets from A to B successfully! Buy tickets from A to B successfully! Buy tickets from A to B successfully! Buy tickets from A to B! Successfully purchased tickets from A to B! Successfully purchased tickets from A to B!......

Prompt all successful purchase tickets! This is obviously unreasonable! Then view the records in the database:

Re-test again, you will find the following output:

成功购买从A到B的车票!成功购买从A到B的车票!成功购买从A到B的车票!成功购买从A到B的车票!成功购买从A到B的车票!成功购买从A到B的车票!成功购买从A到B的车票!成功购买从A到B的车票!成功购买从A到B的车票! Successfully buy tickets from A to B! Buy tickets from A to B! Successful purchase of tickets from A to B! Tickets sold out! Tickets SOLD out! Tickets sold out!.....  Successfully buy tickets from A to B! Buy tickets from A to B successfully! Buy tickets from A to B successfully!....

To view the contents of the database:

Indicates that the result of execution is indeterminate, depending on the speed of execution of each thread.

As can be seen from the above test results, in a similar concurrency situation, the database must be locked, each thread executes the corresponding record lock, to prevent dirty reads appear.

1, the use of pessimistic_write, that is pessimistic write get records, modify the code:

Public Ticket GetTicket (string origin, string destination) {      StringBuilder sb = new StringBuilder ("from Ticket t wher E T.origin =: origin and t.destination =:d estination ");        Query query = entitymanager.createquery (Sb.tostring (), ticket.class);      Query query = entitymanager.createquery (Sb.tostring (), Ticket.class). Setlockmode (lockmodetype.pessimistic_write);      Query.setparameter ("origin", origin);      Query.setparameter ("Destination", destination);      list<ticket> ticketlist = Query.getresultlist ();      if (Ticketlist!=null && ticketlist.size () >0) {         return ticketlist.get (0);      }      return null;}

Execution Result:

Buy tickets from A to B successfully! Buy tickets from A to B successfully! Buy tickets from A to B! Successful purchase of tickets from A to B! Tickets are sold out! Tickets SOLD out! Tickets SOLD out! Tickets sold out!......

Only 5 users buy tickets! Then view the records in the database:

Executed multiple times, the result is only 5 users can successfully purchase tickets, in line with the expected results.

2, the use of Pessimistic_read, that is, pessimistic read to obtain records, the following anomalies will appear:

caused By:com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException:Deadlock found when trying to get lock; Try restarting transaction

Cause: The pessimistic read mechanism means that as long as the transaction reads the DB, the manager locks the DB data until the transaction commits and unlocks, so an exception occurs when the update is made!

Thus, in a similar concurrency situation, pessimistic writing can be used to deal with. However, this approach also has problems, and if the business is complex and processing time is too long, a timeout exception may occur:

caused by:org.hibernate.exception.LockTimeoutException:could not extract ResultSet ... caused by:java.sql.SQLException:Lock wait timeout exceeded; Try restarting transaction

If this happens, there are other ways to deal with it. For example, the operation of the database is handled through stored procedures and so on.

This article link: http://www.codeceo.com/article/db-lock-table.html
This Article code rural network – Li Jie (@lijiejava)

Discussion on locking table in concurrency situation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.