Multi-threaded high concurrency learning thread pool from entry to ground

Near the Chinese New Year, I began to indulge, better for a few days, just back to home at half past twelve at noon today, with my dog son, today is Chinese New Year before the last set, the street is busy, I at noon to eat a meal to go outside for shopping, shopping for a circle, remembered I’ve dove for several days, so I conscience found, hurriedly went back home, open the computer, began to liver.

Without further ado, let’s talk about thread pools from the beginning to the ground

Let’s talk about a few related classes before we get to thread pools

Classes you need to know before entering a thread pool

Executor

Executor is an interface that has only one execute method called execute, which means you can specify a thread to execute its run method

ExecutorService

ExecutorService is an interface that implements the Executor interface and adds many methods, such as **shutdownNow end, isShutdown end, submin commit execution (throw to the thread pool, execute asynchronously)**, and more common methods

Callable

A Callable is equivalent to a Runnable, and a Callable call is equivalent to a Runnable run, except that the call method returns a value and the run method does not

Future

What is Future? The Future is the result of executing the Call method, which will be packaged into the Future. The return type of the Sumin method of the ExecutorService is the Future. When the Get method of the Future is called, it will block, execute, and return

  • Insert a more interesting Future, called FutureTask, which is both an event and a result set. It is equivalent to a combination of Runnable and Future with return values, but requires a new Thread to help it execute, as shown below

Ah, is there anyone who manages multiple tasks?

Hearing this, I cursed, took a sip of cold water, and the clappers cried: Of course!

Next up is CompletableFuture

What the hell is this? CompletableFuture has a static blocking method, allOf, that manages multiple tasks.

Look, I wrote three methods, priceofTM, priceofJD, priceofPDD, all sleep for different seconds, and then let three CompletableFuture execute, and then give one CompletableFuture to manage, and call thisallOfMethod blocks until all methods have executed,It also has an anyOf that unblocks when one execution is complete Ok, that’s all the appetizers, now let’s go dry! MingLog! Hard on the food!

Thread pools from entry to burial

Thread pool parameters

CorePoolSize Specifies the number of core threads

MaximumPoolSize Maximum number of threads allowed to exist (core threads + non-core threads)

KeepAliveTime: When a non-core thread does not execute a task after this time, it is culled and returned to the operating system

TimeUnit TimeUnit: hour, minute, and second

WorkQueue: Various BlockingQueues

ThreadFactory threadFactory: to generate ready-made factories, you need to implement the threadFactory interface

Handler reject policy: When the number of core threads + non-core threads is equal to the maximum number of threads, the handler rejects the policy when applying for more threads

Thread pools execute processes

When the thread pool is initialized, there are no threads in it, so when a task needs to be executed, a core thread is created to execute it, another task is created, and another core thread is created

When creating non-core threads after the number of core threads is reached, you need to check if the core threads are free

If there are free core threads, the task is assigned to the core thread

If there are no free core threads (the core threads are busy), the queue waits for the core thread to finish

If the wait queue is full, a non-core thread is created to execute the task

If a non-core thread does not execute a task beyond the keepAliveTime duration, the non-core thread is culled and returned to the operating system

If core threads + non-core threads = the maximum number of threads, and all threads are busy and no threads are idle, the reject policy is directly implemented when the next task needs to create a thread

BlockingQueue is a queue that can be queued to a queue.blockingQueue is a queue that can be queued to a queue.BlockingQueue is a queue that can be queued to a queue.BlockingQueue is a queue that can be queued to a queue.BlockingQueue is a queued queue

  • If the queue selects LinkedBlockingQueue, we know that it is an unbounded queue that can hold the maximum number of Integer tasks, so your task queue will most likely pile up and only the core thread will work, since non-core threads will only start when the queue is full

  • If the queue selects ArrayBlockingQueue, which is normal, you need to give a task queue length and start non-core threads to execute tasks outside the queue when the backlog reaches a threshold

  • If the queue is set to DelayQueue, it will be sorted by time, so it will be executed by the time the task was created, depending on the compareTo method you rewrote, but! Here we go! This thing is also unbounded, so it’s like LinkedBlockingQueue+ time sort

  • If you select SynchronusQueue, which you know is 0 in length, you have to execute it one by one. After testing, if your thread pool reaches the threshold for adding tasks, it will report an error because tasks cannot be added until the current task has been fetched by the thread

  • If the queue is TransferQueue, it has the same effect as LinkedBlockingQueue

Thread pool rejection policy

If someone asks you, how many rejection strategies are there for a thread pool?

Low EQ answer: 4!

The JDK provides four by default, but we can customize rejection policies!

Boy, the interviewer is calling me a pro

The JDK provides four default reject policies: AbortPolicy, DiscardOldestPolicy, DiscardPolicy, and CallerRunsPolicy

  • AbortPolicy: Simple violence, direct error reporting
  • DiscardOldestPolicy: Discarding the first task in the queue and then adding a new task to it
  • DiscardPolicy: it appears to do nothing, but it secretly kills new quests you want to add
  • CallerRunsPolicy: Give the task you want to add to the main thread

Several common thread pools

Here are a few common thread pools to introduce to you, the interview to the interviewer about, the interviewer straight call expert!

CachedPool

There are no core threads, the maximum number of threads is integer. MAX_VALUE, the lifetime is 60 seconds, and the queue is SynchronousQueue. Each task starts a thread (provided there are no idle threads in the thread pool), and the thread returns after 60 seconds, repeating the process

SingleThreadExecutor

Come on, look at this fun, at first glance, I knock! A core thread, the maximum thread is also one, that is, there is only one thread, lifetime 0, using the LinkedBlockingQueue as queue, one queue at a time to execute

FixedThreadPool

A FixedThreadPool is created with an int as the number of core threads and the maximum number of threads. This means that the pool is full of core threads, and I start each one until it reaches a threshold, and then all the other tasks queue up and wait until the core threads are busy

Specific project actual combat, how much is this thread set reasonable? This should be project-specific

If your project is CPU-intensive (NIO, which only does some computation, not disk), then the number of threads is approximately equal to the number of CPU cores on your server

If your project is IO intensive (less computing, more disk reads and writes), set the number of threads to about 10 times the number of CPU cores

There’s a formula for this thing, I forgot,Specific Settings or to find the most appropriate number of threads until the pressure test data prevail

User-defined rejection policy

Custom rejection policy is very flexible, according to their own business to determine, I directly pseudo code

Several alternative thread pools

The ForkJoinPool types are ThreadPoolExecutor types

WorkStealingPool

A ForkJoinPool is created by creating a new ForkJoinPool, so it is essentially a ForkJoinPool

ForkJoinPool is a system in which each thread has its own queue of tasks to take from the ForkJoinPool. When a thread completes its own queue, it steals tasks from the butt of another queue

ForkJoinPool breaks down large tasks. To what extent? Until the ForkJoinPool meets its own conditions, it splits into twoWell, it said so much, finished, the students have the grave, haven’t the grave, just look at the ThreadPoolExecutor source, understand the deeper, liver for 3 days, this article is not low, I was back home the dog son back, afraid of him eating downstairs, I don’t trust, in my house, he always bother me, ah, it’s too difficult…

Look at me so hard to update the sake of friends don’t whoring for nothing