標籤:案例 imp exce cas AMM pac build ica int
簡要說明:
表設計時,需要往表裡加一個version欄位。每次查詢時,查出帶有version的資料記錄,更新資料時,判斷資料庫裡對應id的記錄的version是否和查出的version相同。若相同,則更新資料並把版本號碼+1;若不同,則說明,該資料發送並發,被別的線程使用了,進行遞迴操作,再次執行遞迴方法,知道成功更新資料為止
簡單說說樂觀鎖。樂觀鎖是相對於悲觀鎖而言。悲觀鎖認為,這個線程,發生並發的可能性極大,線程衝突幾率大,比較悲觀。一般用synchronized實現,保證每次操作資料不會衝突。樂觀鎖認為,線程衝突可能性小,比較樂觀,直接去操作資料,如果探索資料已經被更改(通過版本號碼控制),則不更新資料,再次去重複 所需操作,知道沒有衝突(使用遞迴演算法)。
因為樂觀鎖使用遞迴+版本號碼控制 實現,所以,如果線程衝突幾率大,使用樂觀鎖會重複很多次操作(包括查詢資料庫),尤其是遞迴部分邏輯複雜,耗時和耗效能,是低效不合適的,應考慮使用悲觀鎖。
樂觀鎖悲觀鎖的選擇:
樂觀鎖:並發衝突幾率小,對應模組遞迴操作簡單 時使用
悲觀鎖:並發幾率大,對應模組操作複雜 時使用
案例一
/** * 自動派單 * 只查出一條 返回list只是為了和查詢介面統一 * 視頻審核訂單不派送 * @param paramMap * @return */public List<AutomaticAssignDto> automaticAssign(Map<String, Object> paramMap){//派送規則String changeSortSet = RedisCacheUtil.getValue(CACHE_TYPE.APP, "changeSortSet");if (StringUtils.isBlank(changeSortSet)) {changeSortSet = customerManager.getDictionaryByCode("changeSortSet");if (StringUtils.isNotBlank(changeSortSet)) {RedisCacheUtil.addValue(CACHE_TYPE.APP, "changeSortSet", changeSortSet,30,TimeUnit.DAYS);} else {changeSortSet = ConstantsUtil.AssignRule.FIFO; // 預設先進先審}}AutomaticAssignDto automaticAssignDto = new AutomaticAssignDto();automaticAssignDto.setChangeSortSet(changeSortSet);automaticAssignDto.setUserTeam(CommonUtils.getValue(paramMap, "userTeam"));List<AutomaticAssignDto> waitCheckList = automaticAssignMybatisDao.automaticAssignOrder(automaticAssignDto);if(waitCheckList != null && waitCheckList.size()>0){automaticAssignDto = waitCheckList.get(0);automaticAssignDto.setSendStatus(ConstantsUtil.SendStatus.SEND);automaticAssignDto.setBindTime(new Date());automaticAssignDto.setUserId(Long.parseLong(paramMap.get("userId").toString()) );int sum = automaticAssignMybatisDao.bindAutomaticAssignInfo(automaticAssignDto);if(sum == 1){ return waitCheckList;}else{//已被更新 則再次擷取return automaticAssign(paramMap);}}else{return null;}}
學習自 79594212
案例二
package what21.thread.lock; public class OptimLockMain { // 檔案版本號碼 static int version = 1; // 操作檔案 static String file = "d://IT小奮鬥.txt"; /** * 擷取版本號碼 * * @return */ public static int getVersion(){ return version; } /** * 更新版本號碼 */ public static void updateVersion(){ version+=1; } /** * @param args */ public static void main(String[] args) { for(int i=1;i<=5;i++){ new OptimThread(String.valueOf(i),getVersion(),file).start(); } } } package what21.thread.lock; import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException; public class OptimThread extends Thread { // 檔案版本號碼 public int version; // 檔案 public String file; public OptimThread(String name,int version,String file){ this.setName(name); this.version = version; this.file = file; } public void run() { // 1. 讀取檔案 String text = read(file); println("線程"+ getName() + ",檔案版本號碼為:" + OptimLockMain.getVersion()); println("線程"+ getName() + ",版本號碼為:" + getVersion()); // 2. 寫入檔案 if(OptimLockMain.getVersion() == getVersion()){ println("線程" + getName() + ",版本號碼為:" + version + ",正在執行"); // 檔案操作,這裡用synchronized就相當於檔案鎖 // 如果是資料庫,相當於表鎖或者行鎖 synchronized(OptimThread.class){ if(OptimLockMain.getVersion() == this.version){ // 寫入操作 write(file, text); // 更新檔案版本號碼 OptimLockMain.updateVersion(); return ; } } } // 3. 版本號碼不正確的線程,需要重新讀取,重新執行 println("線程"+ getName() + ",檔案版本號碼為:" + OptimLockMain.getVersion()); println("線程"+ getName() + ",版本號碼為:" + getVersion()); System.err.println("線程"+ getName() + ",需要重新執行。"); } /** * @return */ private int getVersion(){ return this.version; } /** * 寫入資料 * * @param file * @param text */ public static void write(String file,String text){ try { FileWriter fw = new FileWriter(file,false); fw.write(text + "\r\n"); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 讀取資料 * * @param file * @return */ public static String read(String file){ StringBuilder sb = new StringBuilder(); try { File rFile = new File(file); if(!rFile.exists()){ rFile.createNewFile(); } FileReader fr = new FileReader(rFile); BufferedReader br = new BufferedReader(fr); String r = null; while((r=br.readLine())!=null){ sb.append(r).append("\r\n"); } br.close(); fr.close(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } /** * @param content */ public static void println(String content){ System.out.println(content); } }
學習自79337064
Java樂觀鎖的實現原理(案例)