java mail using executorservice

梦想的初衷 提交于 2019-12-11 18:41:26

问题


I am using java mail API.I am able to send emails to individual receipents as,

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. Can anybody let me know what will be approach for implementing executor service here.


回答1:


Use a default executor service getting it from 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).




回答2:


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. Use poll to pop the items off the queue.




回答3:


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

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


来源:https://stackoverflow.com/questions/11408269/java-mail-using-executorservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!