This is the 16th day of my participation in the August More Text Challenge. For details, see:August is more challenging
The thread pool
Benefits/problems solved
- In short, it is reusable. It does not have to be executed by a new thread every time. The creation and destruction of threads are very resource-intensive
- A kind of moderation, because thread pools can limit the number of threads we have, or they can be added dynamically
CTL is an atomic Integer variable that records the state and number of thread pools
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
Copy the code
The class diagram below
Source code analysis
execute
- Execute is used to submit the task command to the thread pool for execution.
- If the task is empty, then it takes too long to throw an exception
- Gets the current thread pool status
- If the number of threads in the current thread pool is less than
corePoolSize
Then we need to start a new thread to run - If the thread pool is in
RUNNING
To add tasks to the blocking queue
private final BlockingQueue<Runnable> workQueue;
Copy the code
4.1 Second Check
4.2 If the task is not in the RUNNING state, delete the task from the queue and execute the rejection policy
If the current thread pool is empty, add a thread
- If the queue is full, a new thread is added, and if the new thread fails, the rejection policy is executed
AddWorker Adds a thread method
6. Check if the queue is empty (only if necessary)
- Loop CAS to increase the number of threads
7.1 False if number of threads exceeds limit
7.2 When the NUMBER of CAS Threads is increased, only one THREAD succeeds in concurrency
7.3 If the CAS fails, check whether the thread pool status changes. If yes, switch to the outer loop and retry to obtain the thread pool status. Otherwise, switch to the inner loop and retry the CAS
- After the loop, this is where the CAS has succeeded
8.1 create a worker
8.2 Added exclusive locks for workers synchronization, because it is possible for multiple threads to simultaneously call the thread pool’s excute method
8.3 Rechecking the thread pool status to avoid calling shutdown before an exclusive lock is obtained