Executors.newCachedThreadPool vs Executors.newSingleThreadExecutor()

public class MyExecutors {

  public static void main(String[] args) {
    ExecutorService ec = Executors.newSingleThreadExecutor();
    long start = System.currentTimeMillis();
    Runnable task = new Runnable() {

      @Override
      public void run() {
        System.out.println(currentThread().getName());
        sleep(1000);
      }
    };

    for (int i = 0; i < 5; i++) {
      ec.execute(task);
    }

    ec.shutdown();
    waitTenSeconds(ec);
    long stop = System.currentTimeMillis();
    System.out.println("Took: " + (stop – start));
  }

  private static void waitTenSeconds(ExecutorService ec) {
    try {
      ec.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  private static void sleep(int value) {
    try {
      Thread.sleep(value);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

The result for Executors.newSingleThreadExecutor() is slow, since every task needs to executed by the same thread:
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
Took: 5006

With Executors.newCachedThreadPool() the result much faster, result is:
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
Took: 1002

In the loop, executor service will create new threads on demand and we don’t need to wait until thread finishes to reuse it.

With Executors.newFixedThreadPool(2) with number of thread set to less than loop count, it will reuse the existing threads, but will not create new one. The result is between newCachedThreadPool() and newSingleThreadExecutor():
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-2
Took: 3005
.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s