简体   繁体   English

使用executorservice的Java邮件

[英]java mail using executorservice

I am using java mail API.I am able to send emails to individual receipents as, 我正在使用Java Mail API。我可以将电子邮件发送给各个收货人,

transport.connect();
for loop {
    member = list.get(i)
    message.setRecipients(MimeMessage.RecipientType.TO, memebr+ "@abc.com");
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
}
transport.close();

The receipents list may be 200,300,500 so on.....Now I want to implement executorservice in above case. 接收者列表可能是200,300,500,依此类推.....现在,我想在上述情况下实现executorservice。 Can anybody let me know what will be approach for implementing executor service here. 有人可以让我知道在这里实现执行者服务的方法是什么。

Use a default executor service getting it from Execturors . 使用默认的执行程序服务从Execturors获取它。 (Preferably not a single threaded.) Then create runnable or callable (if you need some fedback) task that handles the mail sending, taking the varying parts as parameters (addresses, etc.). (最好不是单线程。)然后创建可运行或可调用(如果需要一些反馈)任务来处理邮件发送,将不同部分作为参数(地址等)。 Then loop through just as you did in your example, but instead of calling these lines directly, sumbit a task I previously described in each step. 然后像您在示例中那样循环遍历,但不要直接调用这些行,而是对每个步骤中我之前描述的任务进行汇总。
What you should be careful about is that the mail server might be non thread-safe and also if there is only one mail server, it won't solve the problem since you're constrained on the resources in that case (but the execution won't block in your main thread). 您应该注意的是,邮件服务器可能是非线程安全的,并且如果只有一个邮件服务器,由于在这种情况下您对资源的限制也无法解决问题(但执行会成功)不会阻塞您的主线程)。

The main issue you need to take care of is the concurrent consumption of the mail address list. 您需要注意的主要问题是并发使用邮件地址列表。 Create an object that will hold all data needed for one send operation and put such objects into a ConcurrentLinkedQueue . 创建一个对象,该对象将保存一个发送操作所需的所有数据,并将这些对象放入ConcurrentLinkedQueue Use poll to pop the items off the queue. 使用poll将项目弹出队列。

Sample code look like this:-

ExecutorService executor = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            Member member = list.get(i);
            Runnable worker = new EmailSender(member);
            executor.execute(worker);
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");

In the EmailSender class write the send email function 在EmailSender类中,编写发送电子邮件功能

message.setRecipients(MimeMessage.RecipientType.TO, memebr+ "@abc.com");
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM