What design pattern is used for a thread queue

I have a very complicated system (more than 100 threads) that need to send email without blocking. My solution to the problem was to implement a class called EmailQueueSenderthat starts at the start of execution, and has ScheduledExecutorServiceone that looks at the internal queue every 500 ms, and if size ()> 0, it empties it.

While this happens, there is a synchronized static method addEmailToQueue(String[])that accepts a message containing the body, subject..etc as an array. The system works, and my other threads can move on after adding their email to the queue without blocking or even worrying if the email was sent successfully ... it just seems a little dirty ... or hack ... Every programmer gets this feeling in the stomach when they know that they are doing something wrong or there is a better way. However, can someone hit my wrist and suggest a more effective way to achieve this?

Thank!

+3
source share
5 answers

Java 6, java.util.concurrent.

, , . BlockingQueue, take().

, , append Future, , .

, , ( ) Java- . .

+3

, , . A ThreadPoolExecutor (an ExecutorService -implementation) BlockingQueue , . , ThreadPoolExecutor.

private BlockingQueue<Runnable> queue; 
... 
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, new Long(1000),  
                TimeUnit.MILLISECONDS, this.queue);

, . , ( , ?)

 if (issuedThreads == pool.getCompletedTaskCount()) { 
        pool.shutdown(); 
    } 

, . :

try { 
      while (!this.pool.awaitTermination(1000, TimeUnit.MILLISECONDS)); 
} catch (InterruptedException e) {//log exception...} 
+1

, , , , Spring email . , . .

Spring Java Mail , ThreadPoolExecutor ( @Lorenzo) Quartz. , , , , , cron jobs (, ). Spring , , .

0

There are many packages and tools that will help with this, but the common name of such cases, widely studied in the field of computer science, is a producer-consumer problem . For him, there are various well-known solutions that can be considered as "design patterns".

0
source

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


All Articles