1

I have below function for EWS JAVA API.

public static void cleanRootFolders(String account) throws Exception{

    deleteEmailsFromInbox(account);
    deleteEmailsFromDrafts(account);
    deleteEmailsFromSentItems(account);
    deleteEmailsFromJunkEmails(account);
    deleteEventsFromCalendar(account);
    deleteEmailsFromDeletedItems(account);
}

How can i Implement Thread for performing this Six methods simultaneously for saving the time instead of one after one ?

Gaurav
  • 197
  • 1
  • 7

2 Answers2

1

You can use a thread pool as follows:

ExecutorService executor = Executors.newFixedThreadPool(6);
Runnable r = new Runnable() {
            @Override
            void run() {
                deleteEmailsFromInbox(account);
            }
        }
executor.execute(r)

r = new Runnable() {
            @Override
            void run() {
              deleteEmailsFromDrafts(account);
            }
        }

executor.execute(r)

Or you could simply start a thread for each of the tasks:

Runnable r = new Runnable() {
                @Override
                void run() {
                    deleteEmailsFromInbox(account);
                }
            }
(new Thread(r)).start();
galusben
  • 5,948
  • 6
  • 33
  • 52
1

Below is complete code:

public static void cleanRootFolders(String account) throws Exception{

/*create number of threads  = number of cores. Do note, creating 6 threads doesn't mean 6 threads will work simultaneously.*/

ExecutorService executor = Executors.newFixedThreadPool(numberOfCores);

executor.execute(new Runnable() {
public void run() {
    deleteEmailsFromInbox(account);
}
});

executor.execute(new Runnable() {
public void run() {
    deleteEmailsFromDrafts(account);
}
});

executor.execute(new Runnable() {
public void run() {
    deleteEmailsFromSentItems(account);
}
});

executor.execute(new Runnable() {
public void run() {
    deleteEmailsFromJunkEmails(account);
 }
});

executor.execute(new Runnable() {
public void run() {
    deleteEventsFromCalendar(account);
}
});

executor.execute(new Runnable() {
public void run() {
   deleteEmailsFromDeletedItems(account);
}
});

executor.shutdown(); 
    //always shutdown, so the threads do not keep running.

}
Gaurav
  • 197
  • 1
  • 7
Bikas Katwal
  • 1,895
  • 1
  • 21
  • 42
  • Will it run six methods simultaneously ? – Gaurav Jan 02 '17 at 08:36
  • 1
    yes, all 6 methods will run simultaneously. You can try yourself by writing some print statement with 2sec Thread.sleep time. Synchronously your code would complete in 12 secs approx, whereas using executor service with 6 threads, would complete this code in approx 2 secs. I mentioned here 6 threads because you will be using Thread.sleep and hence 6 threads can run at a time. Thread.sleep doesn't use CPU. Even in above code you can use 6, but personally I prefer creating number of threads based on requirement. – Bikas Katwal Jan 02 '17 at 09:45