SpringBoot如何使用同步锁
今天在实际项目中遇到多线程同步锁记录一下;
第一步 新建SynchrogazerConfig.java 文件 @Slf4j @Component public class SynchrogazerConfig { Map map = new ConcurrentHashMap<>(); public void exec(String key, Runnable runnable) { Object o = map.computeIfAbsent(key, k -> new Object()); synchronized (o) { try { runnable.run(); } catch (Exception e) { log.error("新线程启动失败:{}", e.getMessage()); } finally { map.remove(key); } } } }
这样,基于ConcurrentHashMap线程安全,通过synchronized关键字,封装完成。
第二步 简单测试调用 @Autowired private SynchrogazerConfig sync; @ApiOperation("新增用户") @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity") @PostMapping("/save") public AjaxResult save(UserEntity user) { if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) { return AjaxResult.error("用户ID不能为空"); } sync.exec(String.valueOf(user.getUserId()),()->{ users.put(user.getUserId(), user); }); return AjaxResult.success(); }
问题:这样的使用有什么问题吗?欢迎评论区交流学习!