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

  • 相关阅读:
    shell中使用echo命令改变输出显示样式
    Shell脚本报错unary operator expected
    shell运行报 too many arguments错误
    写shell,运行出错:syntax error near unexpected token `$’do ”
    shell 脚本执行,出现错误bad interpreter: No such file or directory
    Linux 基本命令学习笔记
    如何运行 O’Reilly 书 Python for Finance 的源代码
    IntelliJ 中配置 Anaconda
    Windows 10 中安装 Anaconda 3
    Windows 中安装的 Python 如何卸载
  • 原文地址:https://www.cnblogs.com/thinkingandworkinghard/p/7644048.html
Copyright © 2011-2022 走看看