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:
- Improved response times (reduced time to create new threads).
- Reduce resource consumption (reusing threads from the thread pool, not creating them every time).
- Easy thread management
- CorePoolSize: Size of the core pool
- MaximumPoolSize: indicates the maximum number of threads
- 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
- Void execute(Runnable command) : executes a task or command. No return value is returned. It is used to execute Runnable
- Future Submit (Callable Task): Performs a task, returns a value, and is used to perform a Callable
- Void shutdowm(): closes the connection pool
- Executors: Factory classes for tools and thread pools, used to create and return different types of thread pools.