Java mail send queue - a fixed number of threads sending as many messages as available

I am writing a message processing application (email) that I want to have an outgoing queue. The way I designed this is the singleton queue class, ThreadedQueueSender, supported by the executing service and BlockingQueue. In addition, the javax.mail.Transport object stream pool is used to receive and release connections to the outgoing SMTP server.

This class provides a method add(MimeMessage)that adds messages to the work queue ( BlockingQueue).

When creating an instance of a class ExecutorService, a is initialized ThreadPoolExecutorwith a fixed number of threads, say 5. Each thread run()method is in an infinite loop, which leaves only when an interrupt is detected (when ExecutorService.shutdownNow()).

In this method, run is used BlockingQueue.poll()to receive messages from the work queue until it is available more, without blocking, then it requests an object Transportfrom the connection pool, opens a connection, sends all received messages, closes the connection and returns an object Transport.

This works, but I feel that I am not fully using ExecutorService, having a fixed number of threads that run for the entire duration of the application. In addition, I manage the work queue myself, rather than letting concurrency frameworks handle it. How do others implement this functionality? Is it better to wrap each incoming message in Runnable and then execute the send logic?

Thanks, any comments are appreciated.

Ryan

+3
source share
2 answers

You must create tasks for every job that must be performed by the executor’s service.

, "MailSendingTask", MimeMessage . MailSendingTasks, . , ( , )

2 3 /

  • MailService, (MimeMessage msg)
  • MailServiceImplementation, MailService
  • MailSenderTask , MimeMessage .

, , , MailSenderTask.

"", Future and FutureTask

+1

Runnable , , , . ThreadPoolExecutor . . ThreadPoolExecutor javadoc. - , / -.

, , - , , 4 ThreadPoolExecutor. , .

, BlockingQueue.poll , BlockingQueue.take? , , .

0

Source: https://habr.com/ru/post/1718735/


All Articles