java多线程解决发工资_java多线程处理问题

今天碰到个以前的线上bug需要处理下:问题是这样的,我们的app里面有个点赞的功能,点赞完后显示点赞人列表以及点赞数量,但是数量现在总是不准确。之后查看代码,发现点赞时候只是简单的向数据库添加了一条点赞人的记录和统计记录,但是当多线程的时候和失败的时候,没有做多线程以及回滚处理,因此导致现在的点赞数量和总数总是不能匹配。

想到之前的学过的无锁编程:决定在原来基础上做下处理。

@POST

public ApiResult create(HttpServletRequest request,

@FormParam("topicId") String topicId,

@FormParam("type") String type,

@FormParam("val") String val) {

boolean state = false;

ConcurrentMap result = new ConcurrentHashMap<>(); //使用cas来进行统计 防止出现点赞重复

try {

TopicStatisticsEnum columnType = null;

if (StringUtil.isBlank(topicId)

|| !StringUtil.isNumeric(type)

|| !StringUtil.isNumeric(val)

|| ( columnType = TopicStatisticsEnum.valueOf(Integer.valueOf(type))) == null) {

logger.info("参数错误,注意参数的可填和必填");

result.put(CODE_KEY, Code.PARAM_ILLEGAL);

result.put(MSG_KEY, Code.PARAM_ILLEGAL_MESSAGE);

return new JsonResult(result);

}

state = topicStatisticService.increaseColumnVal(Long.valueOf(topicId), columnType.toString(), getCount(Integer.valueOf(val)));

logger.info("点赞数量值:" + getCount(Integer.valueOf(val)));

result.put(CODE_KEY, state ? Code.SUCCESS : Code.ERROR);

result.put(MSG_KEY, state ? Code.SUCCESS_MESSAGE : Code.ERROR_MESSAGE);

} catch (Exception e) {

e.printStackTrace();

logger.debug("更新话题统计失败");

result.put(CODE_KEY,Code.ERROR);

result.put(MSG_KEY, Code.ERROR_MESSAGE);

}

return new JsonResult(result);

}

AtomicInteger count = new AtomicInteger();

//使用AtomicInteger之后,不需要加锁,也可以实现线程安全。

private int getCount(int val) {

return count.getAndSet(val);

}

使用了cas的方法之后调用AtomicInteger的getAndSet方法设置处理,暂时这么处理,我们的服务是按照分布式来分的,但是分布式事务这块不知道怎么处理了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值