1. 程式人生 > >Java多執行緒系列-悲觀鎖和樂觀鎖實戰

Java多執行緒系列-悲觀鎖和樂觀鎖實戰

悲觀鎖介紹(百科):

悲觀鎖,正如其名,它指的是對資料被外界(包括本系統當前的其他事務,以及來自外部系統的事務處理)修改持保守態度,因此,在整個資料處理過程中,將資料處於鎖定狀態。悲觀鎖的實現,往往依靠資料庫提供的鎖機制(也只有資料庫層提供的鎖機制才能真正保證資料訪問的排他性,否則,即使在本系統中實現了加鎖機制,也無法保證外部系統不會修改資料)。

使用場景舉例:以MySQL InnoDB為例

商品goods表中有一個欄位status,status為1代表商品未被下單,status為2代表商品已經被下單,那麼我們對某個商品下單時必須確保該商品status為1。假設商品的id為1。

1如果不採用鎖,那麼操作方法如下:

//1.查詢出商品資訊

select status from t_goods where id=1;

//2.根據商品資訊生成訂單

insert into t_orders (id,goods_id) values (null,1);

//3.修改商品status為2

update t_goods set status=2;

上面這種場景在高併發訪問的情況下很可能會出現問題。

前面已經提到,只有當goods status為1時才能對該商品下單,上面第一步操作中,查詢出來的商品status為1。但是當我們執行第三步Update操作的時候,有可能出現其他人先一步對商品下單把goods status修改為2了,但是我們並不知道資料已經被修改了,這樣就可能造成同一個商品被下單2次,使得資料不一致。所以說這種方式是不安全的。

2使用悲觀鎖來實現:

在上面的場景中,商品資訊從查詢出來到修改,中間有一個處理訂單的過程,使用悲觀鎖的原理就是,當我們在查詢出goods資訊後就把當前的資料鎖定,直到我們修改完畢後再解鎖。那麼在這個過程中,因為goods被鎖定了,就不會出現有第三者來對其進行修改了。

注:要使用悲觀鎖,我們必須關閉mysql資料庫的自動提交屬性,因為MySQL預設使用autocommit模式,也就是說,當你執行一個更新操作後,MySQL會立刻將結果進行提交。

我們可以使用命令設定MySQL為非autocommit模式:

set autocommit=0;

設定完autocommit後,我們就可以執行我們的正常業務了。具體如下:

//0.開始事務

begin;/begin work;/start transaction; (三者選一就可以)

//1.查詢出商品資訊

select status from t_goods where id=1 for update;

//2.根據商品資訊生成訂單

insert into t_orders (id,goods_id) values (null,1);

//3.修改商品status為2

update t_goods set status=2;

//4.提交事務

commit;/commit work;

注:上面的begin/commit為事務的開始和結束,因為在前一步我們關閉了mysql的autocommit,所以需要手動控制事務的提交,在這裡就不細表了。

上面的第一步我們執行了一次查詢操作:select status from t_goods where id=1 for update;

與普通查詢不一樣的是,我們使用了select…for update的方式,這樣就通過資料庫實現了悲觀鎖。此時在t_goods表中,id為1的 那條資料就被我們鎖定了,其它的事務必須等本次事務提交之後才能執行。這樣我們可以保證當前的資料不會被其它事務修改。

注:需要注意的是,在事務中,只有SELECT ... FOR UPDATE 或LOCK IN SHARE MODE 同一筆資料時會等待其它事務結束後才執行,一般SELECT ... 則不受此影響。拿上面的例項來說,當我執行select status from t_goods where id=1 for update;後。我在另外的事務中如果再次執行select status from t_goods where id=1 for update;則第二個事務會一直等待第一個事務的提交,此時第二個查詢處於阻塞的狀態,但是如果我是在第二個事務中執行select status from t_goods where id=1;則能正常查詢出資料,不會受第一個事務的影響。

補充:MySQL select…for update的Row Lock與Table Lock

上面我們提到,使用select…for update會把資料給鎖住,不過我們需要注意一些鎖的級別,MySQL InnoDB預設Row-Level Lock,所以只有「明確」地指定主鍵,MySQL 才會執行Row lock (只鎖住被選取的資料) ,否則MySQL 將會執行Table Lock (將整個資料表單給鎖住)。

舉例說明:

資料庫表t_goods,包括id,status,name三個欄位,id為主鍵,資料庫中記錄如下;

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods;  
  2. +----+--------+------+  
  3. | id | status | name |  
  4. +----+--------+------+  
  5. |  1 |      1 | 道具 |  
  6. |  2 |      1 | 裝備 |  
  7. +----+--------+------+  
  8. 2 rows in set  
  9. mysql>  
mysql> select * from t_goods;+----+--------+------+| id | status | name |+----+--------+------+|  1 |      1 | 道具 ||  2 |      1 | 裝備 |+----+--------+------+2 rows in setmysql>

注:為了測試資料庫鎖,我使用兩個console來模擬不同的事務操作,分別用console1、console2來表示。 

例1: (明確指定主鍵,並且有此資料,row lock)

console1:查詢出結果,但是把該條資料鎖定了

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where id=1 for update;  
  2. +----+--------+------+  
  3. | id | status | name |  
  4. +----+--------+------+  
  5. |  1 |      1 | 道具 |  
  6. +----+--------+------+  
  7. 1 row in set  
  8. mysql>  
mysql> select * from t_goods where id=1 for update;+----+--------+------+| id | status | name |+----+--------+------+|  1 |      1 | 道具 |+----+--------+------+1 row in setmysql>

console2:查詢被阻塞

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where id=1 for update;  
mysql> select * from t_goods where id=1 for update;

console2:如果console1長時間未提交,則會報錯

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where id=1 for update;  
  2. ERROR 1205 : Lock wait timeout exceeded; try restarting transaction  
mysql> select * from t_goods where id=1 for update;ERROR 1205 : Lock wait timeout exceeded; try restarting transaction

例2: (明確指定主鍵,若查無此資料,無lock)

console1:查詢結果為空

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where id=3 for update;  
  2. Empty set  
mysql> select * from t_goods where id=3 for update;Empty set

console2:查詢結果為空,查詢無阻塞,說明console1沒有對資料執行鎖定

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where id=3 for update;  
  2. Empty set  
mysql> select * from t_goods where id=3 for update;Empty set

例3: (無主鍵,table lock)

console1:查詢name=道具 的資料,查詢正常

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where name='道具' for update;  
  2. +----+--------+------+  
  3. | id | status | name |  
  4. +----+--------+------+  
  5. |  1 |      1 | 道具 |  
  6. +----+--------+------+  
  7. 1 row in set  
  8. mysql>  
mysql> select * from t_goods where name='道具' for update;+----+--------+------+| id | status | name |+----+--------+------+|  1 |      1 | 道具 |+----+--------+------+1 row in setmysql>

console2:查詢name=裝備 的資料,查詢阻塞,說明console1把表給鎖住了

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where name='裝備' for update;  
mysql> select * from t_goods where name='裝備' for update;

console2:若console1長時間未提交,則查詢返回為空

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where name='裝備' for update;  
  2. Query OK, -1 rows affected  
mysql> select * from t_goods where name='裝備' for update;Query OK, -1 rows affected

例4: (主鍵不明確,table lock)

console1:查詢正常

Sql程式碼  收藏程式碼
  1. mysql> begin;  
  2. Query OK, 0 rows affected  
  3. mysql> select * from t_goods where id>0 for update;  
  4. +----+--------+------+  
  5. | id | status | name |  
  6. +----+--------+------+  
  7. |  1 |      1 | 道具 |  
  8. |  2 |      1 | 裝備 |  
  9. +----+--------+------+  
  10. 2 rows in set  
  11. mysql>  
mysql> begin;Query OK, 0 rows affectedmysql> select * from t_goods where id>0 for update;+----+--------+------+| id | status | name |+----+--------+------+|  1 |      1 | 道具 ||  2 |      1 | 裝備 |+----+--------+------+2 rows in setmysql>

console2:查詢被阻塞,說明console1把表給鎖住了

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where id>1 for update;  
mysql> select * from t_goods where id>1 for update;

例5: (主鍵不明確,table lock)

console1:

Sql程式碼  收藏程式碼
  1. mysql> begin;  
  2. Query OK, 0 rows affected  
  3. mysql> select * from t_goods where id<>1 for update;  
  4. +----+--------+------+  
  5. | id | status | name |  
  6. +----+--------+------+  
  7. |  2 |      1 | 裝備 |  
  8. +----+--------+------+  
  9. 1 row in set  
  10. mysql>  
mysql> begin;Query OK, 0 rows affectedmysql> select * from t_goods where id<>1 for update;+----+--------+------+| id | status | name |+----+--------+------+|  2 |      1 | 裝備 |+----+--------+------+1 row in setmysql>

console2:查詢被阻塞,說明console1把表給鎖住了

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where id<>2 for update;  
mysql> select * from t_goods where id<>2 for update;

console1:提交事務

Sql程式碼  收藏程式碼
  1. mysql> commit;  
  2. Query OK, 0 rows affected  
mysql> commit;Query OK, 0 rows affected

console2:console1事務提交後,console2查詢結果正常

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where id<>2 for update;  
  2. +----+--------+------+  
  3. | id | status | name |  
  4. +----+--------+------+  
  5. |  1 |      1 | 道具 |  
  6. +----+--------+------+  
  7. 1 row in set  
  8. mysql>  
mysql> select * from t_goods where id<>2 for update;+----+--------+------+| id | status | name |+----+--------+------+|  1 |      1 | 道具 |+----+--------+------+1 row in setmysql>

以上就是關於資料庫主鍵對MySQL鎖級別的影響例項,需要注意的是,除了主鍵外,使用索引也會影響資料庫的鎖定級別

舉例:

我們修改t_goods表,給status欄位建立一個索引

修改id為2的資料的status為2,此時表中資料為:

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods;  
  2. +----+--------+------+  
  3. | id | status | name |  
  4. +----+--------+------+  
  5. |  1 |      1 | 道具 |  
  6. |  2 |      2 | 裝備 |  
  7. +----+--------+------+  
  8. 2 rows in set  
  9. mysql>  
mysql> select * from t_goods;+----+--------+------+| id | status | name |+----+--------+------+|  1 |      1 | 道具 ||  2 |      2 | 裝備 |+----+--------+------+2 rows in setmysql>

例6: (明確指定索引,並且有此資料,row lock)

console1:

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where status=1 for update;  
  2. +----+--------+------+  
  3. | id | status | name |  
  4. +----+--------+------+  
  5. |  1 |      1 | 道具 |  
  6. +----+--------+------+  
  7. 1 row in set  
  8. mysql>  
mysql> select * from t_goods where status=1 for update;+----+--------+------+| id | status | name |+----+--------+------+|  1 |      1 | 道具 |+----+--------+------+1 row in setmysql>

console2:查詢status=1的資料時阻塞,超時後返回為空,說明資料被console1鎖定了

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where status=1 for update;  
  2. Query OK, -1 rows affected  
mysql> select * from t_goods where status=1 for update;Query OK, -1 rows affected

console2:查詢status=2的資料,能正常查詢,說明console1只鎖住了行,未鎖表

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where status=2 for update;  
  2. +----+--------+------+  
  3. | id | status | name |  
  4. +----+--------+------+  
  5. |  2 |      2 | 裝備 |  
  6. +----+--------+------+  
  7. 1 row in set  
  8. mysql>  
mysql> select * from t_goods where status=2 for update;+----+--------+------+| id | status | name |+----+--------+------+|  2 |      2 | 裝備 |+----+--------+------+1 row in setmysql>

例7: (明確指定索引,若查無此資料,無lock)

console1:查詢status=3的資料,返回空資料

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where status=3 for update;  
  2. Empty set  
mysql> select * from t_goods where status=3 for update;Empty set

console2:查詢status=3的資料,返回空資料

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods where status=3 for update;  
  2. Empty set  
mysql> select * from t_goods where status=3 for update;Empty set

談到了MySQL悲觀鎖,但是悲觀鎖並不是適用於任何場景,它也有它存在的一些不足,因為悲觀鎖大多數情況下依靠資料庫的鎖機制實現,以保證操作最大程度的獨佔性。如果加鎖的時間過長,其他使用者長時間無法訪問,影響了程式的併發訪問性,同時這樣對資料庫效能開銷影響也很大,特別是對長事務而言,這樣的開銷往往無法承受。所以與悲觀鎖相對的,我們有了樂觀鎖,具體參見下面介紹:

樂觀鎖介紹:

樂觀鎖( Optimistic Locking ) 相對悲觀鎖而言,樂觀鎖假設認為資料一般情況下不會造成衝突,所以在資料進行提交更新的時候,才會正式對資料的衝突與否進行檢測,如果發現衝突了,則讓返回使用者錯誤的資訊,讓使用者決定如何去做。那麼我們如何實現樂觀鎖呢,一般來說有以下2種方式:

1.使用資料版本(Version)記錄機制實現,這是樂觀鎖最常用的一種實現方式。何謂資料版本?即為資料增加一個版本標識,一般是通過為資料庫表增加一個數字型別的 “version” 欄位來實現。當讀取資料時,將version欄位的值一同讀出,資料每更新一次,對此version值加一。當我們提交更新的時候,判斷資料庫表對應記錄的當前版本資訊與第一次取出來的version值進行比對,如果資料庫表當前版本號與第一次取出來的version值相等,則予以更新,否則認為是過期資料。用下面的一張圖來說明:

如上圖所示,如果更新操作順序執行,則資料的版本(version)依次遞增,不會產生衝突。但是如果發生有不同的業務操作對同一版本的資料進行修改,那麼,先提交的操作(圖中B)會把資料version更新為2,當A在B之後提交更新時發現數據的version已經被修改了,那麼A的更新操作會失敗。

2.樂觀鎖定的第二種實現方式和第一種差不多,同樣是在需要樂觀鎖控制的table中增加一個欄位,名稱無所謂,欄位型別使用時間戳(timestamp), 和上面的version類似,也是在更新提交的時候檢查當前資料庫中資料的時間戳和自己更新前取到的時間戳進行對比,如果一致則OK,否則就是版本衝突。

使用舉例:以MySQL InnoDB為例

還是拿之前的例項來舉:商品goods表中有一個欄位status,status為1代表商品未被下單,status為2代表商品已經被下單,那麼我們對某個商品下單時必須確保該商品status為1。假設商品的id為1。

下單操作包括3步驟:

1.查詢出商品資訊

select (status,status,version) from t_goods where id=#{id}

2.根據商品資訊生成訂單

3.修改商品status為2

update t_goods 

set status=2,version=version+1

where id=#{id} and version=#{version};

那麼為了使用樂觀鎖,我們首先修改t_goods表,增加一個version欄位,資料預設version值為1。

t_goods表初始資料如下:

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods;  
  2. +----+--------+------+---------+  
  3. | id | status | name | version |  
  4. +----+--------+------+---------+  
  5. |  1 |      1 | 道具 |       1 |  
  6. |  2 |      2 | 裝備 |       2 |  
  7. +----+--------+------+---------+  
  8. rows in set  
  9. mysql>  
mysql> select * from t_goods;
+----+--------+------+---------+
| id | status | name | version |
+----+--------+------+---------+
|  1 |      1 | 道具 |       1 |
|  2 |      2 | 裝備 |       2 |
+----+--------+------+---------+
2 rows in set

mysql>

對於樂觀鎖的實現,我使用MyBatis來進行實踐,具體如下:

Goods實體類:

Java程式碼  收藏程式碼
  1. /** 
  2.  * ClassName: Goods <br/> 
  3.  * Function: 商品實體. <br/> 
  4.  * date: 2013-5-8 上午09:16:19 <br/> 
  5.  * @author [email protected] 
  6.  */  
  7. public class Goods implements Serializable {  
  8.     /** 
  9.      * serialVersionUID:序列化ID. 
  10.      */  
  11.     private static final long serialVersionUID = 6803791908148880587L;  
  12.     /** 
  13.      * id:主鍵id. 
  14.      */  
  15.     private int id;  
  16.     /** 
  17.      * status:商品狀態:1未下單、2已下單. 
  18.      */  
  19.     private int status;  
  20.     /** 
  21.      * name:商品名稱. 
  22.      */  
  23.     private String name;  
  24.     /** 
  25.      * version:商品資料版本號. 
  26.      */  
  27.     private int version;  
  28.     @Override  
  29.     public String toString(){  
  30.         return "good id:"+id+",goods status:"+status+",goods name:"+name+",goods version:"+version;  
  31.     }  
  32.     //setter and getter  
  33. }  
/**
 * ClassName: Goods <br/>
 * Function: 商品實體. <br/>
 * date: 2013-5-8 上午09:16:19 <br/>
 * @author [email protected]
 */
public class Goods implements Serializable {

	/**
	 * serialVersionUID:序列化ID.
	 */
	private static final long serialVersionUID = 6803791908148880587L;
	
	/**
	 * id:主鍵id.
	 */
	private int id;
	
	/**
	 * status:商品狀態:1未下單、2已下單.
	 */
	private int status;
	
	/**
	 * name:商品名稱.
	 */
	private String name;
	
	/**
	 * version:商品資料版本號.
	 */
	private int version;
	
	@Override
	public String toString(){
		return "good id:"+id+",goods status:"+status+",goods name:"+name+",goods version:"+version;
	}

	//setter and getter

}

GoodsDao

Java程式碼  收藏程式碼
  1. /** 
  2.  * updateGoodsUseCAS:使用CAS(Compare and set)更新商品資訊. <br/> 
  3.  * 
  4.  * @author [email protected] 
  5.  * @param goods 商品物件 
  6.  * @return 影響的行數 
  7.  */  
  8. int updateGoodsUseCAS(Goods goods);  
/**
 * updateGoodsUseCAS:使用CAS(Compare and set)更新商品資訊. <br/>
 *
 * @author [email protected]
 * @param goods 商品物件
 * @return 影響的行數
 */
int updateGoodsUseCAS(Goods goods);

mapper.xml

Xml程式碼  收藏程式碼
  1. <update id="updateGoodsUseCAS" parameterType="Goods">  
  2.     <![CDATA[ 
  3.         update t_goods 
  4.         set status=#{status},name=#{name},version=version+1 
  5.         where id=#{id} and version=#{version} 
  6.     ]]>  
  7. </update>  
<update id="updateGoodsUseCAS" parameterType="Goods">
	<![CDATA[
		update t_goods
		set status=#{status},name=#{name},version=version+1
		where id=#{id} and version=#{version}
	]]>
</update>

GoodsDaoTest測試類

Java程式碼  收藏程式碼
  1. @Test  
  2. public void goodsDaoTest(){  
  3.     int goodsId = 1;  
  4.     //根據相同的id查詢出商品資訊,賦給2個物件  
  5.     Goods goods1 = this.goodsDao.getGoodsById(goodsId);  
  6.     Goods goods2 = this.goodsDao.getGoodsById(goodsId);  
  7.     //列印當前商品資訊  
  8.     System.out.println(goods1);  
  9.     System.out.println(goods2);  
  10.     //更新商品資訊1  
  11.     goods1.setStatus(2);//修改status為2  
  12.     int updateResult1 = this.goodsDao.updateGoodsUseCAS(goods1);  
  13.     System.out.println("修改商品資訊1"+(updateResult1==1?"成功":"失敗"));  
  14.     //更新商品資訊2  
  15.     goods1.setStatus(2);//修改status為2  
  16.     int updateResult2 = this.goodsDao.updateGoodsUseCAS(goods1);  
  17.     System.out.println("修改商品資訊2"+(updateResult2==1?"成功":"失敗"));  
  18. }  
@Test
public void goodsDaoTest(){
	int goodsId = 1;
	//根據相同的id查詢出商品資訊,賦給2個物件
	Goods goods1 = this.goodsDao.getGoodsById(goodsId);
	Goods goods2 = this.goodsDao.getGoodsById(goodsId);
	
	//列印當前商品資訊
	System.out.println(goods1);
	System.out.println(goods2);
	
	//更新商品資訊1
	goods1.setStatus(2);//修改status為2
	int updateResult1 = this.goodsDao.updateGoodsUseCAS(goods1);
	System.out.println("修改商品資訊1"+(updateResult1==1?"成功":"失敗"));
	
	//更新商品資訊2
	goods1.setStatus(2);//修改status為2
	int updateResult2 = this.goodsDao.updateGoodsUseCAS(goods1);
	System.out.println("修改商品資訊2"+(updateResult2==1?"成功":"失敗"));
}

輸出結果:

Shell程式碼  收藏程式碼
  1. good id:1,goods status:1,goods name:道具,goods version:1  
  2. good id:1,goods status:1,goods name:道具,goods version:1  
  3. 修改商品資訊1成功  
  4. 修改商品資訊2失敗  
good id:1,goods status:1,goods name:道具,goods version:1
good id:1,goods status:1,goods name:道具,goods version:1
修改商品資訊1成功
修改商品資訊2失敗

說明:

在GoodsDaoTest測試方法中,我們同時查出同一個版本的資料,賦給不同的goods物件,然後先修改good1物件然後執行更新操作,執行成功。然後我們修改goods2,執行更新操作時提示操作失敗。此時t_goods表中資料如下:

Sql程式碼  收藏程式碼
  1. mysql> select * from t_goods;  
  2. +----+--------+------+---------+  
  3. | id | status | name | version |  
  4. +----+--------+------+---------+  
  5. |  1 |      2 | 道具 |       2 |  
  6. |  2 |      2 | 裝備 |       2 |  
  7. +----+--------+------+---------+  
  8. rows in set  
  9. mysql>   
mysql> select * from t_goods;
+----+--------+------+---------+
| id | status | name | version |
+----+--------+------+---------+
|  1 |      2 | 道具 |       2 |
|  2 |      2 | 裝備 |       2 |
+----+--------+------+---------+
2 rows in set

mysql> 

我們可以看到 id為1的資料version已經在第一次更新時修改為2了。所以我們更新good2時update where條件已經不匹配了,所以更新不會成功,具體sql如下:

Sql程式碼  收藏程式碼
  1. update t_goods   
  2. set status=2,version=version+1  
  3. where id=#{id} and version=#{version};  
update t_goods 
set status=2,version=version+1
where id=#{id} and version=#{version};

這樣我們就實現了樂觀鎖


參考資料:

MySQL事務與鎖定命令:http://www.docin.com/p-16805970.html

悲觀鎖:http://www.cnblogs.com/chenwenbiao/archive/2012/06/06/2537508.html