美文网首页
Javamail 改造成多线程

Javamail 改造成多线程

作者: 憨人Zoe | 来源:发表于2018-04-04 21:21 被阅读0次

    前几天改造完成的邮件拨测项目又改需求了,leader 希望能改造成多线程下运行,以email为维度收集日志。
    但是改造过程并不顺利,首先改造成多线程很简单,先上代码:

        //创建全局线程池
        private ExecutorService threadPool = Executors.newCachedThreadPool();
    
        //job
        public void sendEmail() {
            //省略若干配置...
    
            //读取配置的测试邮箱信息,包括protocol,email,pwd,host等等
            SONArray emailArr = getEmailsArray();
    
            //CountDownLatch 
            CountDownLatch countDownLatch = new CountDownLatch(emailArr.size());
    
            //遍历邮箱
            for (int j = 0; j < emailArr.size(); j++) {
                final JSONObject obj = emailArr.getJSONObject(j);
                //加入线程池
                threadPool.execute(() -> {
                    Map<String, String> indexedTags = new HashMap<>();
                    Map<String, String> storedTags = new HashMap<>();
                    indexedTags.put("module", "记录日志模块名");
                    try {
                        String proto = obj.getString("protocol");
                        String email = obj.getString("email");
                        String pass = obj.getString("pass");
                        String host = obj.getString("host");
                        String uuid = UUID.randomUUID().toString();
    
                        SendEmailTool sendEmailTool = new SendEmailTool();
                        sendEmailTool.setFrom(sender);
                        sendEmailTool.setTo(email);
                        sendEmailTool.setTemplateId(Integer.parseInt(templateId));
                        sendEmailTool.setSubject("uuid:" + uuid);
                        //发邮件
                        SendEmailResponse response = sendEmailTool.sendEmail();
                        //发送状态
                        boolean sent = (response != null && response.getResultCode() == 1);
                        //记录发送状态
                        storedTags.put("sent", sent ? "1" : "0");
                        //记录email
                        indexedTags.put("email", getEmailSupplierWithUnderLine(email));
                        //等待接收
                        Thread.sleep(Integer.valueOf(waitTime));
                        //开始接收
                        List<EmailEntity> list = ReceiveEmailTool.getEmailList(proto, email, pass, host, deleteFlag, socksProxyHost, socksProxyPort, timeout);
                        //接收状态
                        boolean received = false;
                        for (EmailEntity entity : list) {
                            if (entity.getSubject() != null && entity.getSubject().startsWith("uuid:") && entity.getSubject().contains(uuid)) {
                                received = true;
                            }
                        }
                        //记录接收状态
                        storedTags.put("received", received ? "1" : "0");
                        //记录ack 状态
                        indexedTags.put("ack", (sent && received) ? "1" : "0");
                    } catch (Throwable e) {
                        //记录异常信息
                        indexedTags.put("ack", "0");
                        indexedTags.put("exception", StreamUtility.toString(e));
                    } finally {
                        countDownLatch.countDown();
                        //写日志
                    }
                });
            }
            //等待线程全部结束
            countDownLatch.await();
            //job 完成
        }
    

    这一版改完直接发布运行,发现第一批次的7个线程,只有5个完成并输出了日志,然后job不知道什么原因卡住了。分析无果,只得本地调试。发现finally 写日志的地方抛出来异常。这是公司的基础组件引起的线程安全问题。于是修复bug,再次发布运行。

    重点来了
    运行一段时间,查看日志,发现失败率异常的高。远远高于改造之前,查看日志异常信息,发现不同的邮箱catch 到的异常居然相同,hotmail的异常竟然输出了qq的帮助地址,肯定是线程串了。于是再次查看代码,线程池改造这里应该是没有问题,问题可能出在抛异常的类。

    检查 ReceiveEmailToolgetEmailList 方法,发现

        // 获取连接
        Session session = Session.getDefaultInstance(props);
    

    进入 getDefaultInstance 方法发现

        public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator) {
            if(defaultSession == null) {
                defaultSession = new Session(props, authenticator);
            } else if(defaultSession.authenticator != authenticator && (defaultSession.authenticator == null || authenticator == null || defaultSession.authenticator.getClass().getClassLoader() != authenticator.getClass().getClassLoader())) {
                throw new SecurityException("Access to default session denied");
            }
    
            return defaultSession;
        }
    

    该类下面还有另2个方法

        public static Session getInstance(Properties props, Authenticator authenticator) {
            return new Session(props, authenticator);
        }
    
        public static Session getInstance(Properties props) {
            return new Session(props, (Authenticator)null);
        }
    

    原来,由于我改造成了多线程,当线程A应实例化了session对象以后,线程B将直接返回A实例化的seesion,导致线程串并。
    将代码替换为

        Session session = Session.getInstance(props);
    

    再次发布运行,发现依然没有解决。这又是为什么?再次检查代码,发现还有一个共享的变量

        Properties props = System.getProperties();
    

    这是当初使用全局代理时遗留下来的。若非如此,直接new 就好了

        Properties props = new Properties();
    

    再次发布,问题解决。

    相关文章

      网友评论

          本文标题:Javamail 改造成多线程

          本文链接:https://www.haomeiwen.com/subject/orylhftx.html