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 ) {
Also, note: if you do not want to have a headache - the sendMailTo method must be stateless.
stemm source share