Java ExecutorService Implementation Assistance

橙三吉。 提交于 2019-12-12 00:17:02

问题


In the following code, userList gets high volume of data due to which sending email takes too long time.

How can I speed up the application such that 50000 emails are sent faster? Maybe with the use of an 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
    }
}

回答1:


Try parallelize your code in such 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 don't want to have a headache - method sendMailTo must be stateless.




回答2:


You could do such 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

  • You can find it's java doc here.
  • A more detailed tutorial about ExecutorService is available here.


来源:https://stackoverflow.com/questions/12302114/java-executorservice-implementation-assistance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!