Hi, I’m Excutors, an honest tool class.

If someone had talked about thread pools like that before, I would have understood! He dug a hole and said he would introduce me to everyone.

I actually quite grievance, as a feeling, honest work tool class, BUT I went up alibaba’s blacklist. They wrote in a book called the Java Development Manual:

Author voice-over: somebody else why screen for you, don’t write clearly, you have what can be wronged. And you this guy is the appearance of honesty, the job is you do? It’s not all ThreadPoolExecutor. Here, I’ll count them for you.

1. newFixedThreadPool

A FixedThreadPool is a fixed size thread pool.

Take a look at the source code implementation:

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
Copy the code

Call the constructor of ThreadPoolExecutor directly.

  • Core threadsandMaximum number of threadsThe same
  • useLinkedBlockingQueueAs a task queue

Execute () in FixedThreadPool

Overall operation process:

  • Fewer threads are currently runningcorePoolSize, a new thread is created to execute the task
  • The current running thread is greater thancorePoolSize, add the taskLinkedBlockingQueue
  • Threads in the thread pool loop from the thread pool after completing tasksLinkedBlockingQueueTo obtain the task execution

Because unbounded queue LinkedBlockingQueue is used to store tasks that cannot be executed, denial of service policies are not triggered and may result in OOM.

2. newSingleThreadExecutor

SingleThreadExecutor is a thread pool that works with a single thread.

The implementation source code is as follows:

    public static ExecutorService newSingleThreadExecutor(a) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1.1.0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
Copy the code

Call the constructor of ThreadPoolExecutor directly.

  • Core threadsandMaximum number of threadsIs 1
  • useLinkedBlockingQueueAs a task queue

SingleThreadExecutor runtime flow:

  • There is currently no running thread. Create a thread to execute the task
  • A thread is currently running, adding a taskLinkedBlockingQueue
  • After the thread completes the task, it loops fromLinkedBlockingQueueTo execute

This uses the unbounded queue LinkedBlockingQueue, which may also result in OOM.

3. newCachedThreadPool

CachedThreadPool is a thread pool that creates new threads as needed.

Implementation source code:

    public static ExecutorService newCachedThreadPool(a) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
Copy the code

Call the constructor of ThreadPoolExecutor directly.

  • Core threadsIs zero,Maximum number of threadsIt’s a very large numberInteger.MAX_VALUE
  • Use without capacitySynchronousQueueAs a work queue
  • keepAliveTimeIf set to 60L, idle threads are terminated after 60 seconds

CachedThreadPool CachedThreadPool

  • If there are currently free threads, use the free thread to execute the task
  • If there are no free threads, create a new thread to execute the task
  • The task will be executed after the newly created thread completes the taskPoll (keepAliveTime, timeunit.nanoseconds)In theSynchronousQueueWaiting in the 60 s

There is no limit to the size of the thread pool, which can create threads indefinitely, resulting in OOM.

4. newScheduledThreadPool

ScheduledThreadPool is a thread pool with scheduling capabilities.

Implementation source code:

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
Copy the code

As you can see, this thread pool is not too same, it is called ScheduledThreadPoolExecutor constructor.

    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }
Copy the code
  • The maximum number of threads isInteger.MAX_VALUEInfinity,
  • useDelayedWorkQueueAs a task queue

ScheduledThreadPoolExecutor mission process:

It is mainly divided into two parts:

  1. callscheduleAtFixedRate()/scheduleWithFixedDelay()Method, will be directed toDelayQueueAdd aScheduledFutureTask.
  2. Thread pool threads fromDelayQueueTo deriveScheduledFutureTask“And then execute the mission.

It can also create threads indefinitely, so there is also OOM risk.

In order to realize the periodic task, ScheduledThreadPoolExecutor [4] to some ThreadPoolExecutor transform:

  • ScheduledFutureTask is used as the implementation of the scheduling task

    It contains three member variables: time(the specific time of the task to be executed), sequenceNumber (the number of the task), and Period (the interval of the task execution).

  • Use DelayQueue as the task queue

    DelayQueue encapsulates a PriorityQueue, which sorts scheduledFutureTasks in the queue with a priority of time>sequenceNumber.

ScheduledThreadPoolExecutor’s main task is divided into four steps:

  1. In the thread poolThread 1fromDelayQueueTo obtain the expiredScheduledFutureTask(DelayQueue. Take ())
  2. Thread 1To perform thisScheduledFutureTask
  3. Thread 1Modify theScheduledFutureTaskthetimeThe variable is the next time it will be executed.
  4. Thread 1I’m going to change thistimeAfter theScheduledFutureTaskPut it backDelayQueue(DelayQueue. The add ())

Excutors: This, this… Problems with utility classes are not called bugs. Even though I’m lazy and might get OOM, I’m still a good tool class, whoo-hoo…

Akik Yeah, what’s wrong with Excutors? It’s just a tool class with no feelings, only the people who use it incorrectly are at fault. So, know and know why, understand the principle, flexible application. We should be like a soldier, not only able to pull the trigger, but also able to disarm and maintain the gun.

I am three points evil, a so-called full stack of literary and military development.

Like, pay attention to not get lost, let’s see you next time!



Reference:

[1]. The Art of Concurrent Programming in Java

[2]. Let’s be honest. This is a great time to learn about thread pools

[3]. “Java Face Book Manual”

[4]. The Beauty of Concurrent Programming in Java

[5]. Java Development Manual of Alibaba