Javamail 改造成多线程

前几天改造完成的邮件拨测项目又改需求了,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();

再次发布,问题解决。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,242评论 25 708
  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 2,493评论 1 15
  • h市一地下研究所内,一操作台上躺着一位成年男性,k博士正和他的学生们小心翼翼地将从一只变异猫妖体内取出的“能源...
    末日兔子阅读 702评论 0 0
  • 国庆长假结束,据说今年的假期到此全部用完。那回归的第一天就干脆给大家推荐一部电影吧! 最为国人所知的有关自闭症的电...
    菩提扣阅读 1,001评论 0 1
  • 依然清晰的记得自习室里那忙忙碌碌的三个多月,每天三点一线,忙碌而又充实。每当情绪不佳思想开小差的时候,找一曲...
    小蜜蜂娟子阅读 604评论 9 22