Java concurrency Executors.newCachedThreadPool()

import static java.lang.Thread.currentThread;
import static java.util.concurrent.Executors.newCachedThreadPool;

public class MyExecutors {

  public static void main(String[] args) {
    ExecutorService es = newCachedThreadPool();
    Runnable task = new Runnable() {

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

    for (int i = 0; i < 5; i++) {
      es.execute(task);
      sleep(500); // 1
    }
    exec.shutdown();
  }

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

Result – reusing cached treads:
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1

After removing sleep(500) for the loop (// 1), we immediately need 5 threads and reuse is not possible:
pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-4
pool-1-thread-5

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