Junior — Middle
How to determine the number of threads created within a thread pool?
sobes.tech AI
Answer from AI
In Java, the number of threads in a pool is determined at its creation, usually through constructor parameters or factory methods of the ThreadPoolExecutor class.
For example, when creating a fixed thread pool using Executors.newFixedThreadPool(int nThreads), a pool with a fixed number of threads nThreads is created.
If ThreadPoolExecutor is used, then the number of threads is controlled by the parameters:
corePoolSize— the minimum number of threads that are always maintainedmaximumPoolSize— the maximum number of threads that can be created if needed
Example of creating a pool with a fixed number of threads:
ExecutorService executor = Executors.newFixedThreadPool(5); // 5 threads
Or using ThreadPoolExecutor:
ThreadPoolExecutor executor = new ThreadPoolExecutor(
3, // corePoolSize
10, // maximumPoolSize
60, TimeUnit.SECONDS, // keep-alive time
new LinkedBlockingQueue<>()
);
Thus, to determine the number of threads, you should look at the pool creation parameters, especially corePoolSize and maximumPoolSize.