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<String, Object> 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方法设置处理,暂时这么处理,我们的服务是按照分布式来分的,但是分布式事务这块不知道怎么处理了。

posted @ 2017-10-10 09:33  Doyourself!  阅读(592)  评论(0编辑  收藏  举报