A thread pool is, as the name suggests, a pool of threads.

Why do thread pools exist?

  • The frequent creation and destruction of threads can have an impact on machine performance. If we can reuse threads, avoiding frequent creation and destruction can reduce the performance loss of the computer.
  • Core parameters of the thread pool?
    • Core threads
    • Maximum number of threads
    • Thread lifetime
    • Waiting queue length
    • Thread pool rejection policy
  • Task scheduling mechanism?
    • If the number of current threads is less than the number of core threads, then the core thread executes
    • If the number of current threads is greater than the number of core threads, the queue is entered
    • If the wait queue is full, the maximum number of threads is created
    • If there are already the maximum number of threads in the thread pool and the wait queue is full, the reject policy is implemented.
  • Blocking queue
    • ArrayBlocking is based on arrays
    • LinkedBlocking is based on linked lists
    • Prior priority queue
  • Rejection policies
    • AbortPolicy rejects it outright
    • DiscardPolicy Discards the task
    • DiscardOldestPolicy Discards the most recent task
    • CallerRunsPolicy The calling thread continues with the task.
  • Thread pool tuning?
    • Differentiate business background
      • A quick response
        • The thread pool should not have a wait queue, and increase the number of core threads and maximum threads to create as many threads as possible to execute tasks quickly
      • Fast batch task
        • Offline the massive computing tasks, don’t need a quick response, our relationship is how to use limited resources as far as possible more processing tasks in unit time, we should set the waiting queue, the appropriate adjust the core thread, excessive number of threads can also cause the thread context switching frequent problems, will also reduce the speed of the task, reduce throughput
  • Thread pool parameter Settings
    • IO intensive
      • Features the CPU waiting time is 2n +1
    • CPU intensive
      • Features Long CPU execution time n+1
    • Formula: Optimal number of threads: [(thread wait time + thread CPU time)/thread wait time] * number of CPU cores
    • The higher the waiting time of a thread, the more threads are needed; the less the waiting time, the fewer threads are needed.
  • Thread pool dynamic parameter Settings
    • Dynamic parameter setting.