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