Introduction to the Java thread pool

Source: Internet
Author: User

Introduction to the Java thread pool2015-10-24 importnew

(Click on the upper number to quickly follow)

Original: Allegro

Translation: IMPORTNEW-PADDX

Links: http://www.importnew.com/16845.html

According to Moore's law, the number of transistors in an IC is almost doubled every two years. But an exponential increase in the number of transistors does not necessarily lead to exponential growth in CPU performance. Processor manufacturers have spent many years improving clock frequency and instruction parallelism. On a new generation of processors, the execution rate of single-threaded threads has indeed improved. However, the clock frequency cannot be increased indefinitely, as the processor AMD FX-9590 clock frequency reaches 5 GHz, which is already very difficult. Processor manufacturers now prefer multi-core processors (multi-core processors). Smartphones with 4 cores are already commonplace, not to mention laptops and desktops. As a result, the software has to be multithreaded so that it can better use the hardware. The thread pool can help programmers make better use of multicore CPUs.

Thread pool

Good software design is not recommended for manually creating and destroying threads. The creation and destruction of threads is very CPU-and memory-intensive, as this requires the involvement of the JVM and the operating system. The 64-bit JVM default line stacks is 1 MB in size. This is why it is a waste of resources to create threads for each small request when the request is frequent. The thread pool can automatically process the life cycle of threads based on the policy selected at the time of creation. The point is that the thread pool has no obvious advantage in the case of resources (such as memory, CPU), or no thread pool will cause the server to collapse. There are a number of reasons why there are no more resources available. For example, many threads that are caused by a denial of service (Denial-of-service) attack are executed in parallel, resulting in thread starvation (thread starvation). In addition, the programmer must remember to handle this exception when the thread is manually executed, and the thread may die because of an exception.

Even though the thread pool is not explicitly used in your app, Web servers like Tomcat and undertow use a large number of thread pools. So it is very helpful to understand how the thread pool works and how it is tuned to optimize system performance.

The thread pool can be easily created by the Executors factory method. The classes that implement Executorservice in the JDK are:

    • Forkjoinpool

    • Threadpoolexecutor

    • Scheduledthreadpoolexecutor

These classes all implement the thread pool abstraction. The following small piece of code shows the life cycle of the Executorservice:

Public list<future<t>> executetasks (collection<callable<t>> tasks) {

Create an Executorservice

Create Executorservice

Final Executorservice Executorservice = Executors.newsinglethreadexecutor ();

Execute All Tasks

Perform All Tasks

Final list<future<t>> executedtasks = Executorservice.invokeall (tasks);

Shutdown the Executorservice after all tasks has completed

Close Executorservice after all tasks have been executed

Executorservice.shutdown ();

return executedtasks;

}

First, create a single-threaded actuator (executor) with the simplest executorservice--. It uses a thread to handle all the tasks. Of course, you can also customize Executorservice in a variety of ways, or use the executors class's engineering methods to create Executorservice:

Newcachedthreadpool (): Creates a executorservice that Executorservice creates threads as needed, and can reuse existing threads to perform tasks.

Newfixedthreadpool (int numberofthreads): Creates a reusable, fixed number of threads Executorservice.

Newscheduledthreadpool (int corepoolsize): Creates Executorservice (or periodically creates executorservice) after a given time, depending on the time schedule.

Newsinglethreadexecutor (): Creates a single worker thread executorservice.

Newsinglethreadscheduledexecutor (): Creates a single worker thread Executorservice (or periodic creation) based on the time schedule delay.

Newworkstealingpool (): Creates a executorservice that has multiple task queues (to reduce the number of connections).

In the above example, all tasks are performed only once, and you can use other methods to perform the task:

    • void Execute (Runnable)

    • Future Submit (callable)

    • Future Submit (Runnable)

Finally, close the Executorservice. Shutdown () is a non-blocking method. When this method is called, Executorservice enters "shutdown mode (shutdown mode)", in which the previously submitted task will complete, but will not receive new tasks. If you want to wait for the task to finish, you need to call the Awaittermination () method.

Executorservice is a very useful tool that can help us to perform all tasks conveniently. Where is the benefit of it? We do not need to create worker threads manually. A worker thread is a thread used internally by Executorservice. It is worth noting that Executorservice manages the life cycle of threads. It can increase the worker thread when the load increases. On the other hand, it can also reduce idle threads for a certain period of time. When we use the thread pool, we no longer have to think about the threads themselves. We only need to consider the task of asynchronous processing. In addition, when unexpected exceptions occur, we no longer need to create threads repeatedly, nor do we need to worry about reuse when a thread finishes executing a task. Finally, after a task is submitted, we can obtain an abstract--future of future results. Of course, in Java 8, we can use better completablefuture, and how to convert a future to completablefuture is beyond the scope of this article. But keep in mind that the future only makes sense when the task being submitted is a callable, because callable has output, and Runnable does not.

Internal composition

Each thread pool consists of several modules:

    • A task queue,

    • A collection of worker threads,

    • A thread factory,

    • Manages metadata for thread state.

There are many implementations of the Executorservice interface, and we focus on the most commonly used threadpoolexecutor. In fact, the Newcachedthreadpool (), Newfixedthreadpool (), and Newsinglethreadexecutor () Three methods return instances of the Threadpoolexecutor class. If you want to manually create an instance of the Threadpoolexecutor class, you need at least 5 parameters:

    • int Corepoolsize: The number of threads saved by the thread pool.

    • int maximumpoolsize: The maximum number of threads.

    • Long keepAlive and Timeunit unit: After the corepoolsize size is exceeded, the thread is idle for a given amount of time and will close.

    • Blockingqueue WorkQueue: The submitted task will be placed in the queue for execution.

    • Thread-pool

blocking queues

Linkedblockingqueue is the default queue used when calling methods in the Executors class to generate Threadpoolexecutor instances, Priorityblockingqueue is actually a blockingqueue, However, dealing with tasks based on the set priorities is also a tricky issue. First, submit a Runnable or callable task, which is packaged as a runnablefuture and then added to the queue, Prorityblockingqueue Compare each object to determine the priority of execution (the comparison object is the wrapped runnablefuture instead of the contents of the task). Not only that, when Corepoolsize is greater than 1 and the worker thread is idle, threadpoolexecutor may be executed according to the order of insertion, rather than the order of precedence expected by Priorityblockingqueue.

By default, Threadpoolexecutor's work queue (workQueue) has no boundaries. This is usually fine, but keep in mind that a work queue without boundaries can cause an application to have a memory overflow (out of the memories) error. If you want to limit the size of the task queue, you can set Rejectionexecutionhandler. You can customize the processor or choose one of the 4 existing processors (the default AbortPolicy):

    • Callerrunspolicy

    • AbortPolicy

    • Discardpolicy

    • Discardoldestpolicy

Thread Factory

Thread factories are typically used to create custom threads. For example, you can add a custom thread.uncaughtexceptionhandler or set a thread name. In the following example, an uncaught exception is logged using the thread name and the sequence number of the thread.

public class Loggingthreadfactory implements Threadfactory {

private static final Logger Logger = Loggerfactory.getlogger (Methodhandles.lookup (). Lookupclass ());

private static final String Thread_name_prefix = "worker-thread-";

Private final Atomicinteger Threadcreationcounter = new Atomicinteger ();

@Override

Public Thread Newthread (Runnable Task) {

int threadnumber = Threadcreationcounter.incrementandget ();

Thread workerthread = new Thread (task, Thread_name_prefix + threadnumber);

Workerthread.setuncaughtexceptionhandler (thread, Throwable, Logger.error ("thread {} {}", Thread.getname (), Throwable));

return workerthread;

}

}

Examples of producer consumers

Producer consumers are a common problem with simultaneous multithreading. In this example, we use Executorservice to solve this problem. However, this is not a textbook example of solving the problem. Our goal is to demonstrate the thread pool to handle all synchronization problems so that programmers can focus on implementing business logic.

Producer periodically gets new data from the database to create the task and submit the task to Executorservice. A worker thread in a Executorservice managed thread pool represents a Consumer that handles business tasks such as calculating prices and returning them to customers.

First, we use Spring to configure:

@Configuration

public class Producerconsumerconfiguration {

<a href= ' http://www.jobbole.com/members/weibo_1902876561 ' > @Bean </a>

Public Executorservice Executorservice () {

Single Consumer

return Executors.newsinglethreadexecutor ();

}

Other beans such as a data source, a scheduler, etc.

}

Then, establish a Consumer and a consumerfactory. The engineering method is used by the producer to create a task that, at some point in the future, will have a worker thread perform the task.

public class Consumer implements Runnable {

Private final Businesstask Businesstask;

Private final businesslogic businesslogic;

Public Consumer (Businesstask businesstask, Businesslogic businesslogic) {

This.businesstask = Businesstask;

This.businesslogic = Businesslogic;

}

@Override

public void Run () {

Businesslogic.processtask (Businesstask);

}

}

@Component

public class Consumerfactory {

Private final businesslogic businesslogic;

Public consumerfactory (Businesslogic businesslogic) {

This.businesslogic = Businesslogic;

}

Public Consumer Newconsumer (Businesstask businesstask) {

return new Consumer (Businesstask, businesslogic);

}

}

Finally, there is a Producer class that is used to fetch data from the database and create business tasks. In this example, we assume that Fetchdata () is called periodically through scheduler.

@Component

public class Producer {

Private final datarepository datarepository;

Private final Executorservice Executorservice;

Private final consumerfactory consumerfactory;

@Autowired

Public Producer (Datarepository datarepository, Executorservice Executorservice,

Consumerfactory consumerfactory) {

This.datarepository = datarepository;

This.executorservice = Executorservice;

This.consumerfactory = consumerfactory;

}

public void fetchandsubmitforprocessing () {

list<data> Data = Datarepository.fetchnew ();

Data.stream ()

Create a business task from data fetched from the database

. Map (Businesstask::fromdata)

Create a consumer for each business task

. Map (Consumerfactory::newconsumer)

Submit the task for further processing of the future (Submit is a non-blocking method)

. ForEach (Executorservice::submit);

}

}

Thanks Executorservice so we can focus on the business logic and we don't need to worry about syncing. The demo code above uses only one producer and one consumer. However, it is easy to expand the situation for multiple producers and multiple consumers.

Summarize

JDK 5 was born in 2004 and offers many useful concurrency tools, one of which is the Executorservice class. Thread pools are typically applied to the underlying servers (such as Tomcat and Undertow). Of course, the thread pool is not confined to the server environment. They are very useful in any dense parallel (embarrassingly parallel) challenge. As more and more software runs on multicore systems, the thread pool deserves more attention now.

Introduction to the 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.