Java Concurrency : ExecutorService

Andrea Huang
3 min readJun 30, 2021
  • 1 Java thread = 1 OS thread
  • 1 OS thread is running on 1 core
  • usually create fixed number of threads and assign task to the threads
  • code in the task need to be thread-safe
  • For CPU intensive task, number of thread should= number CPU cores
  • For IO intensive task, number of thread should be high to accommodate the task submission rate/ wait time (SLA). But too many threads will increase memory consumption

4 Types of Thread Pool

  1. FixedThreadPool (Blocking Queue is used)

2. SingleThreadPool (Blocking Queue is used) (recreate thread if killed because of the task) (tasks will be executed in sequence.

3. CachedThreadPool (Synchronous Queue, only hold 1 task) (create new one if needed, and put the thread to the pool. If a thread idle for more than 60 seconds, will be killed)

4. ScheduledThreadPool (Delay Queue)

  • schedule(): can schedule to start the task after certain delay
  • scheduleAtFixedRate(new Task(), $initialDelay, TimeUnit): start after certain delay and start every xx period
  • scheduleAtFixedDelay(new Task(), $initialDelay, $delayAfterComplete, TimeUnit): run the task after certain delay, wait for another delay period after the task to complete, and rerun the task

Pool Size

Queue Type

Rejection Policy

Lifecycle Management

service.shutdown() ;// not accept new task, will complete all submitted tasks

List<Runnable> runnables = service.shutdownNow(); // start shutdown and return all queued tasks.

service.awaitTermination(xx,TimeUnit);//block until all tasks are completed, or if timeout

service.isShutdown();// check if shutdown has begun

service.isTerminated();//

Task that return result : Callable

Interface : runnable vs callable

Future<Integer> future =service.submit(new Task());

Integer result = future.get(); // blocking method: like await

Reference:

--

--

Andrea Huang

我的Patrick是個6歲的小男孩。我想記錄下此時我想與他分享的感悟。雖然他此時未必能理解,但是等到適當的時機,他可以讀到來自媽媽當年的分享