I'm writing a message processing application (email) that I want to have an outgoing queue. The way I've designed this is having a singleton queue class, ThreadedQueueSender, backed by an Executor Service and a BlockingQueue. Additionally, a thread pool of javax.mail.Transport objects is used to obtain and release connections to the outgoing SMTP server.
This class exposes a method, add(MimeMessage), that adds messages to the work queue (BlockingQueue).
At instantiation of the class, the ExecutorService is initialized to a ThreadPoolExecutor with a fixed number of threads, lets say 5. Each thread's run() method is in infinite loop that only exits when it detects interrupt (when ExecutorService.shutdownNow() is called).
This run method uses BlockingQueue.poll() to take messsages from the work queue until no more are available without blocking, then requests a Transport object from the connection pool, opens the connection, sends all the messages its retrieved, closes the connection and returns the Transport object.
This works, but I feel I am not taking full advantage of the ExecutorService by having a fixed number of threads that run for the life of the application. Also, I am managing the work queue myself instead of letting the concurrency frameworks handle it. How would others implement this functionality? Is it better to wrap each incoming message in a Runnable, then execute the sending logic?
Thank you, any comments are appreciated.
Ryan
解决方案
You should create tasks for every piece of work that should be done by your executor service.
For example you could create a callable "MailSendingTask" that holds the MimeMessage and wraps the mail sending. Queue these MailSendingTasks by submitting them to your executor. Now your Executor decides how many threads will be created (Config it by setting lower and upper thread pool bounds)
You only need to create 2 or 3 classes/interfaces
one MailService Interface that provides a simple send(MimeMessage msg) method
one MailServiceImplementation Class that implements MailService and holds a reference to a configured executor
one class MailSenderTask implementing the callable interface that holds a reference to the MimeMessage object and which does the mail sending.
You could even go futher by creating an extra service that manages the mail socket connections which could be used by the MailSenderTask.
If you want to add "cancelation" you should look at the classes Future and FutureTask
该博客讨论了一种实现邮件处理应用程序的方法,通过使用Singleton队列类、ExecutorService和BlockingQueue来管理邮件发送。作者考虑是否应该为每个邮件创建一个Runnable任务,并利用ExecutorService的灵活性来动态调整线程池大小,而不是固定数量的线程。建议将邮件发送逻辑封装在Callable任务中,提交给ExecutorService,同时提出可能创建单独的服务来管理邮件SMTP连接池,以提高效率并支持取消操作。

被折叠的 条评论
为什么被折叠?



