Help implementing Java ExecutorService

In the following code, userList receives a large amount of data, which makes sending a message too long.

How to speed up the application so that 50,000 emails are sent faster? Maybe using ExecutorService ?

 List<String[]> userList = new ArrayList<String[]>(); void getRecords() { String [] props=null; while (rs.next()) { props = new String[2]; props[0] = rs.getString("useremail"); props[1] = rs.getString("active"); userList.add(props); if (userList.size()>0) sendEmail(); } void sendEmail() { String [] user=null; for (int k=0; k<userList.size(); k++) { user = userList.get(k); userEmail = user[0]; //send email code } } 
0
source share
2 answers

Try to decompose your code this way:

 private final int THREADS_NUM = 20; void sendEmail() throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool( THREADS_NUM ); for ( String[] user : userList ) { final String userEmail = user[0]; executor.submit( new Runnable() { @Override public void run() { sendMailTo( userEmail ); } } ); } long timeout = ... TimeUnit timeunit = ... executor.shutdown(); executor.awaitTermination( timeout, timeunit ); } void sendMailTo( String userEmail ) { // code for sending e-mail } 

Also, note: if you do not want to have a headache - the sendMailTo method must be stateless.

+3
source

You can accomplish such a task using ExecutorService as follows:

 ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { public void run() { System.out.println("Asynchronous task"); /* Add your logic here */ } }); executorService.shutdown(); 

INFO

  • Here you can find java doc here .
  • A more detailed guide to ExecutorService available here .
0
source

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


All Articles