Java 悲观锁 synchronized (member){代码块}

Java 如果遇到会出现高并发的情况,一般建议使用悲观锁 :synchronized (member){代码块}  需要对数据库进行修改或新增的时候,建议写上事务--@Transactional

@Transactional

public Map<String, Object> saveCode(Member member, SessionRecord sr) {

// TODO Auto-generated method stub

log.getLogger("dbeleven2020_s").info("saveCode-response params1:({}),params2:({})", member, sr);

Map<String, Object> resp = new HashMap<String, Object>();

Map<String, Object> codeMap = new HashMap<String, Object>();

synchronized (member) {

codeMap.put("accountId", member.getAccountId());

// 这里要判断一下,该会员,是否有过sharecode

String hasCode = "";

String code = "";

hasCode = doubleEleven2020Mapper.selectIsHadCode(codeMap);

if (StringUtils.isEmpty(hasCode)) {

code = shareCodeService.generateShareCode(16);

codeMap.put("shareCode", code);

if (doubleEleven2020Mapper.addCode(codeMap) == 1) {

log.getLogger("dbeleven2020_s").info("addCode-response params1:({}),params2:({})", codeMap, true);

resp.put("shareCode", code);

}

}

else {

resp.put("shareCode", hasCode);

}

resp.put("status", true);

}

return resp;

}

posted @ 2020-10-21 13:51  夏之  阅读(240)  评论(0编辑  收藏  举报