Thread synchronization--Pessimistic lock

Source: Internet
Author: User

In the case of database access, there is a problem: two threads accessing the same object at the same time can cause data inconsistency, so what we need to do is add the lock.


First Scenario:Synchronized


Java used to lock objects and methods or code. , when he locks a method or a block of code , At most one thread at a time executes the code . when two concurrent threads access the same object in this lock-and-sync block of code , only one thread gets it within a single time , Another thread must wait for the current thread to execute this block of code before executing the code block .


Usage:Synchronized Join method and Synchronized(this) the two meanings are the same, both are lock the object.


Implementation method:


<span style= "FONT-SIZE:18PX;" ><p>public staticsynchronized int Generatate (stringtablename) {//Pessimistic lock with database for updatestring sql = "Select value From t_table_id where table_name=? "; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null;int value=0;try {conn = dbutil.getconnection ();D butil.begintransaction (conn);p stmt = Conn.preparestatement (SQL);p stmt.setstring (1,tablename), rs = Pstmt.executequery (), if (!rs.next ()) {throw new RuntimeException ();} Value = Rs.getint ("value"); Value++;modifyvaluefield (Conn,tablename,value);} catch (SQLException e) {e.printstacktrace ();} Finally {Dbutil.close (RS);D butil.close (pstmt);D butil.close (conn);} return value;} </p></span>

Or we can write this:


<span style= "FONT-SIZE:18PX;" >public synchronized int  generatate (String tableName) {synchronized (this) {</span>


The second scenario: Pessimistic lock


You can use pessimistic locks in the database, for example: SELECT * FROM T_TABLE_ID where table_name? Form update, pessimistic lock is implemented by the database mechanism, after the data is locked, other users will not be able to view until the lock is released, only the commit or rollback thing lock will be released. The FOR UPDATE statement can only be placed in the SELECT statement, because it makes sense to lock the data when queried.


We encapsulate data rollback:


<span style= "FONT-SIZE:18PX;" >public static void BeginTransaction (Connection conn) {try{if (conn!= null) {if (Conn.getautocommit ()) { Conn.setautocommit (FALSE); Manually Submit}}}catch (SQLException e) {}}</span>

To encapsulate the submission of a thing:


<span style= "FONT-SIZE:18PX;" >public static void CommitTransaction (Connection conn) {try{if (conn!= null) {if (!conn.getautocommit ()) {Conn.commit ();}}} catch (SQLException e) {}}</span>

Encapsulate a thing rollback:


<span style= "FONT-SIZE:18PX;" >public static void Rollbacktracsaction (Connection conn) {try{if (conn!= null) {if (!conn.getautocommit ()) { Conn.rollback ();}}} catch (SQLException e) {}}</span>

Encapsulate things Reset:


<span style= "FONT-SIZE:18PX;" >public static void Ressetconnection (Connection conn) {try{if (conn!= null) {if (Conn.getautocommit ()) { Conn.setautocommit (false);} Else{conn.setautocommit (True);}}} catch (SQLException e) {}}</span>


Test using:


<span style= "FONT-SIZE:18PX;" >public static int  generatate (String tableName) {//Use pessimistic lock for database for updatestring sql = ' Select value from t_table_id where Table_name=? For update "; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null;int value=0;try {conn = dbutil.getconnection ();D butil.begintransaction (conn);p stmt = Conn.preparestatement (SQL);p stmt.setstring (1,tablename), rs = Pstmt.executequery (), if (!rs.next ()) {throw new RuntimeException ();} Value = Rs.getint ("value"); Value++;modifyvaluefield (conn,tablename,value);//Submit thing dbutil.committransaction (conn);} catch (SQLException e) {e.printstacktrace ();//Rollback thing dbutil.rollbacktracsaction (conn);} Finally {Dbutil.close (RS);D butil.close (pstmt);D butil.ressetconnection (conn);//recharge to Connection status Dbutil.close (conn );} return value;} </span>

Summary:


The data in the database is priceless, pessimistic lock , has the strong exclusive and exclusive characteristic , has the conservative attitude to the data by the outside modification . in this data processing process , lock data in a locked state , This is the implementation of the pessimistic lock .


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Thread synchronization--Pessimistic lock

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.