Using thread pools

  • Background: The frequent creation and destruction of extremely large resources, such as threads in the case of concurrency, can have a significant impact on performance.
  • Create several threads in advance and put them into the thread pool.
  • Benefits:
    1. Improved response times (reduced time to create new threads).
    2. Reduce resource consumption (reusing threads from the thread pool, not creating them every time).
    3. Easy thread management
      1. CorePoolSize: Size of the core pool
      2. MaximumPoolSize: indicates the maximum number of threads
      3. KeepAliveTime: The maximum amount of time a thread can hold without a task before terminating
  • JDK5.0 provides thread pool-related apis: ExecutorService and Executors
  • ExecutorService: A true thread pool interface. A common subclass, ThreadPoolExecutor
    1. Void execute(Runnable command) : executes a task or command. No return value is returned. It is used to execute Runnable
    2. Future Submit (Callable Task): Performs a task, returns a value, and is used to perform a Callable
    3. Void shutdowm(): closes the connection pool
  • Executors: Factory classes for tools and thread pools, used to create and return different types of thread pools.