Java thread pool

Source: Internet
Author: User

Multi-Threading Practice paged Query

Multithreading is a good thing, with good performance can be greatly improved. Before writing a page for a paged query, the approximate model is this:

Want to a paged query, but also want to bring out the b,c,d,e information, the first is not a multi-threaded, forced query in addition to a list, and then traverse the elements of a, and then query out the corresponding B,c,d and E. When I looked at the request time, there was probably a 700~800ms, and it was really slow to see the naked eye. Then think about not, or use multithreading optimization, and then the query and a related table information Task division, to different thread processing, after the assembly data is finished, the main thread will return the final list to the foreground. The last query time is reduced to about 160ms.

Why you need to use a thread pool

If the thread pool is not used, the approximate way to use threads is this:

Every time you use a thread, you have to create an instance of a thread, and then destroy it after it is finished, and the thread is also called Lightweight in Linux, and although there is a lightweight prefix, its creation and destruction also consumes system resources. Imagine creating dozens of threads at a time, destroying them after using them, and then creating more than 10 threads and then destroying them, the performance loss is very objective (this is scaring you for a while, because I haven't measured them yet). In addition to the overhead of creating and destroying threads, the active thread consumes system resources. Creating too many threads in one JVM can cause the system to run out of memory or "over-switch" because of excessive memory consumption.

Benefits of the thread pool:

    • Enables thread reuse, reducing the overhead associated with creating threads repeatedly
    • The thread is available as soon as the task arrives, eliminating the delay caused by threading creation and responding faster

This design idea can be seen in many places:

    • An integer's enjoy meta design pattern
    • Connection pool for Database

are based on performance considerations.

What is the relationship between Java threads and processes in the operating system?

Let's keep this.

The thread pool in Java

You'll often see four thread pools in Java when you're looking at blogs:

But today went to see the source of the next java.util.concurrent.Executors, found that it seems more than four kinds of ah, and then online to see the next there are seven kinds!

    • Newcachedthreadpool: Creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.
    • Newfixedthreadpool: Create a fixed number of thread pools that can be reused.
    • Newscheduledthreadpool: Create a fixed-length pool that supports timed and recurring task execution.
    • Newsinglethreadexecutor: Creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).
    • Newsinglethreadscheduledexcutor: Create a singleton thread pool to perform tasks on a regular or deferred basis.
    • Newworkstealingpool: Create a thread pool that holds enough threads to support a given level of parallelism, and reduce contention by using multiple queues, it needs to wear a parallel-level parameter, and if not, it is set to the default number of CPUs.
    • Forkjoinpool: A thread pool that supports large-task decomposition into small tasks, which is a Java8 new thread pool that is typically used with subclasses recursiveaction or recursivetask of forkjointask interfaces.
Creation of the thread pool

Several of these are created through the class java.util.concurrent.ThreadPoolExecutor, and there are several ways to construct it, and here's a typical analysis:

1  PublicThreadpoolexecutor (intCorepoolsize,2                           intMaximumpoolsize,3                           LongKeepAliveTime,4 timeunit Unit,5Blockingqueue<runnable>workQueue) {6      This(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue,7 executors.defaultthreadfactory (), defaulthandler);8}

Parameter explanation:

    • Corepoolsize: Always keep the number of threads in the thread pool, even if they are idle, and will not go unless you set the Allowcorethreadtimeout
    • Maximumpoolsize: Maximum number of threads allowed in the thread pool
    • KeepAliveTime: When the number of threads in a thread pool is more than the core, this is the longest time to wait for a new task, and once more threads are recycled
    • Unit:keepalivetime Unit of Time
    • WorkQueue: A task that has not yet been assigned thread execution enters the wait queue, and only when the runnable task is committed by the Execute method does it enter the queue
    • Threadfactory:executor the factory used to create a new thread
    • Handler: Policy taken when execution is blocked
Corepoolsize

The size of the core pool, this parameter is very much related to the implementation principle of the thread pool described later. After the thread pool has been created, by default, there are no threads in the thread pools, instead of waiting for a task to be created to perform the task, unless the prestartallcorethreads () or Prestartcorethread () method is called. As you can see from the names of these 2 methods, the meaning of the pre-created thread is to create a corepoolsize thread or a thread before the task arrives. By default, after the thread pool has been created, the number of threads in the threads pools is 0, and when a task comes, a thread is created to perform the task, and when the number of threads in the thread pool reaches corepoolsize, the incoming task is placed in the cache queue.

Maximumpoolsize

The maximum number of threads in the thread pool, which is also a very important parameter, which indicates the maximum number of threads that can be created in a thread pool;

KeepAliveTime

Indicates how long the thread will stay when no task is executed. By default, KeepAliveTime only works if the number of threads in the thread pool is greater than corepoolsize, until the number of threads in the thread pool is not greater than corepoolsize, that is, when the number of threads in the thread pool is greater than corepoolsize. If a thread is idle for KeepAliveTime, it terminates until the number of threads in the thread pool does not exceed corepoolsize. However, if the Allowcorethreadtimeout (Boolean) method is called, the KeepAliveTime parameter also works when the number of threads in the thread pool is not greater than corepoolsize, until the number of threads in the thread pool is 0;

Unit

The time unit of the parameter KeepAliveTime, there are 7 kinds of values, there are 7 static properties in the Timeunit class:

1 // days 2 // hours 3 // minutes 4 // seconds 5 // milliseconds 6 // Subtle 7 // na-Sec
WorkQueue

A blocking queue, which is used to store tasks waiting to be executed, and the choice of this parameter is also important to have a significant impact on the running process of the thread pool, in general, there are several options for blocking queues here:

1 Arrayblockingqueue 2 Linkedblockingqueue 3 Synchronousqueue

Arrayblockingqueue and Priorityblockingqueue use less, generally using linkedblockingqueue and synchronous. The thread pool's queuing policy is related to Blockingqueue.

Threadfactory

Thread factory, used primarily to create threads;

Handler

Represents the following four types of values when a policy is rejected when processing a task:

123Threadpoolexecutor.discardoldestpolicy: Discards the task at the front of the queue, Then retry the task (Repeat this procedure)4 threadpoolexecutor.callerrunspolicy: The task is handled by the calling thread
Java thread pool classes, interfaces, and methods

How do you block the main thread when using the thread pool so that the threads in the thread pools finish the task, then the main thread executes?

How do I design a thread pool?

How do I make the thread pool more efficient?

What are the open source thread pooling implementations?

How do I determine the number of threads in a thread pool?

Reference
    • 48342253
    • Https://www.cnblogs.com/dolphin0520/p/3932921.html
    • Https://www.cnblogs.com/YFYkuner/p/5178684.html
    • https://baike.baidu.com/item/MVCC/6298019
    • Https://www.cnblogs.com/chenpingzhao/p/5065316.html

Java thread pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.