SpringBoot 如何使用同步锁

今天在实际项目中遇到多线程同步锁记录一下;
第一步 新建SynchrogazerConfig.JAVA 文件
@Slf4j@Componentpublic class SynchrogazerConfig {Map<String, Object> 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关键字,封装完成 。
【SpringBoot 如何使用同步锁】第二步 简单测试调用
@Autowiredprivate SynchrogazerConfig sync;@ApiOperation("新增用户")@ApiImplicitParam(name = "userEntity", value = https://www.isolves.com/it/cxkf/jiagou/2022-01-24/"新增用户信息", 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();}问题:这样的使用有什么问题吗?欢迎评论区交流学习!




    推荐阅读