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

  • 相关阅读:
    [引]Windows窗体编程基础学习: 对话框组件
    UML学习四:UML在微软的VS与Visio间的应用 VEA(Visio for Enterprise Architects)
    SQL查询 FOR XML [RAW|AUTO|EXPLICIT]
    微软企业类库:Enterprise Library for .NET Framework 2.0 January 2006
    自定义制作 自动定时更换图片的桌面背景 html页面
    [引]Windows Server 2003 : Windows 群集
    LOVE
    SQL Server Mobile 学习(三):SQL Server Mobile 远程数据访问(RDA)
    游戏分类
    [摘]UML学习二:标准建模语言UML的静态建模机制
  • 原文地址:https://www.cnblogs.com/thinkingandworkinghard/p/7644048.html
Copyright © 2011-2022 走看看