thread pool anaylsis

queue1.gif
queue2.gif
queue3.jpg

properties

private final BlockingQueue workQueue;

private final ReentrantLock mainLock = new ReentrantLock();

private volatile long keepAliveTime;

private volatile boolean allowCoreThreadTimeOut;

private volatile int corePoolSize;

private volatile int maximumPoolSize;

private volatile int poolSize;

execute judgement

1
2
3
4
5
6
7
8
9
10
11
public void execute(Runnable command) {
if (command == null) throw new NullPointerException();
if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
if (runState == RUNNING && workQueue.offer(command)) {
if (runState != RUNNING || poolSize == 0)
ensureQueuedTaskHandled(command);
}
else if (!addIfUnderMaximumPoolSize(command))
reject(command); // is shutdown or saturated
}
}

thread judgement

1
2
3
4
5
6
7
8
9
10
11
12
private boolean addIfUnderCorePoolSize(Runnable firstTask) {
Thread t = null;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (poolSize < corePoolSize && runState == RUNNING)
t = addThread(firstTask);
} finally {
mainLock.unlock();
}
return t != null;
}

add thread

1
2
3
4
5
6
7
8
9
10
11
12
13
private Thread addThread(Runnable firstTask) {

// similar to new Thread(Runnable);
Worker w = new Worker(firstTask);
Thread t = threadFactory.newThread(w);
...
int nt = ++poolSize;
if (nt > largestPoolSize) largestPoolSize = nt;
...
t.start();
...
return t;
}

Inner class Worker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private final class Worker implements Runnable {
...
private void runTask(Runnable task) {
...
task.run();
...
}
public void run() {
...
while (task != null || (task = getTask()) != null) {
runTask(task);
task = null;
}
...
workerDone(this);
}
}

get task from queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Runnable getTask() {
for (;;) {
...
Runnable r;
if (state == SHUTDOWN) // Help drain queue
r = workQueue.poll();
else if (poolSize > corePoolSize || allowCoreThreadTimeOut)
r = workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS);
else
r = workQueue.take();
if (r != null)
return r;
...
}
}

the design of thread pool

Has no specific thread to dispatch task.

If still have task in QlockingQueue,
when thread’s task done, it will fetch task in queue itself.

If still no task in QlockingQueue, and task has done.
In worker’s run() - workerDone(this); call to terminate itself.

https://www.cnblogs.com/heyanan/p/9261695.html
http://www.cnblogs.com/dolphin0520/p/3932921.html