Use of the Java thread pool

Source: Internet
Author: User
Tags terminates

Overview

The disadvantages of new thread are as follows:
A. Each new thread creates a poor performance for the newly created object.
B. Lack of unified management of threads, the possibility of unlimited new threads, competing with each other, and potentially consuming excessive system resources can lead to freezing or oom.
C. Lack of additional functionality, such as timed execution, periodic execution, and thread interruption.

if the number of concurrent threads is large, and each thread is executing a short task, then the frequent creation of threads can greatly reduce the efficiency of the system because it takes time to create threads and destroy threads frequently. So is there a way to enable a thread to be reused, to perform a task, not to be destroyed, but to continue to perform other tasks? This can be achieved through the thread pool in Java .

Java thread Pool

Java provides four thread pools through executors, namely:
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 creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
Newscheduledthreadpool creates a fixed-line 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).

Regardless of which method is created, the final return is Threadpoolexecutor, and the method return is Executorservice, Threadpoolexecutor inherited the Abstractexecutorservice, and Abstractexecutorservice realized the Executorservice interface,
Executorservice This interface inherits the executor. threadpoolexecutor is-aexecutorservice.

threadpoolexecutor Construction Method

The thread pool class is java.util.concurrent.ThreadPoolExecutor and is commonly constructed by:
Threadpoolexecutor (

int corepoolsize,//thread Pool maintains minimum number of threads

int maximumpoolsize,//Thread pool maintains the maximum number of threads

Long keepalivetime,//thread pool to maintain idle time allowed by threads

Timeunit unit,//thread pool maintains the units of idle time allowed by threads

Blockingqueue<runnable> WorkQueue,// buffer queue used by the thread pool,

Mainly used Arrayblockingqueue, Linkedblockingqueue, Synchronousqueue

Threadfactory threadfactory,//Thread Factory

Rejectedexecutionhandler handler// thread pool processing policy for rejected tasks

)

the detailed meaning of the parameter:
corepoolsize: The size of the core pool. After creating the thread pool, by default, there are no threads in the thread pools, but wait for a task to come before creating the thread to perform the task, unless the prestartallcorethreads () or Prestartcorethread () method is called, which means the pre-created thread , which is to create corepoolsize threads or a thread before a 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: Thread pool Maximum number of threads, this parameter is also a very important parameter that represents the maximum number of threads that can be created in a thread pool.
KeepAliveTime: Indicates the maximum length of time a thread will be terminated without a task executing. 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 kinds of static properties in the Timeunit class:
Timeunit.days; Days
timeunit.hours; Hours
Timeunit.minutes; Minutes
Timeunit.seconds; Seconds
Timeunit.milliseconds; Milliseconds
Timeunit.microseconds; Subtle
Timeunit.nanoseconds; Na-Sec
WorkQueue: A blocking queue that stores the 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, where the blocking queue has the following options:
Arrayblockingqueue;
Linkedblockingqueue;
Synchronousqueue;
Arrayblockingqueue and Priorityblockingqueue use less, generally using linkedblockingqueue and synchronous. The thread pool's queuing policy is related to Blockingqueue.
threadfactory: Thread factory, mainly used to create threads;
Handler: Represents the following four types of values when a policy is rejected when processing a task:
Threadpoolexecutor.abortpolicy: Discards the task and throws a rejectedexecutionexception exception.
Threadpoolexecutor.discardpolicy: Also discards the task, but does not throw an exception.
Threadpoolexecutor.discardoldestpolicy: Discards the first task in the queue and then tries to perform the task again (repeat this process)
Threadpoolexecutor.callerrunspolicy: The task is handled by the calling thread

Submit a Task

We can use the task submitted by execute, but the Execute method does not return a value, so it is not possible to determine whether the task was successfully executed by the thread pool.

Threadspool.execute (New Runnable () {            @Override public            void Run () {                //TODO auto-generated method stub            }        });
We can also use the Submit method to submit the task, it will return a future, then we can determine whether the task succeeds, through the future of the Get method to get the return value, the Get method will block until the task is completed, and use Get (long Timeout, Timeunit unit) method will be blocked for a period of time immediately after the return, it is possible that the task is not finished.

future<object> future = Executor.submit (Harreturnvaluetask); try {     Object s = future.get ();} catch ( Interruptedexception e) {    //handle Interrupt exception} catch (Executionexception e) {    //handle cannot perform task exception} finally {    //shutdown thread pool    exe Cutor.shutdown ();}

Terminating the thread pool

Threadpoolexecutor provides two methods for closing the thread pool, respectively, shutdown () and Shutdownnow (), Where:
Shutdown (): Does not terminate the thread pool immediately, but waits until all tasks in the task cache queue have been executed before terminating, but will no longer accept new tasks
Shutdownnow (): Terminates the thread pool immediately, attempts to break the task in progress, and empties the task cache queue, returning tasks that have not yet been performed

How to choose a reasonable thread pool

Compute-intensive, is the application needs a lot of CPU computing resources, in the multi-core CPU era, we want each CPU core to participate in the calculation, the CPU performance fully utilized, so that is not wasted service configuration, if the very good configuration is still running a single-threaded application that would be a huge waste. For compute-intensive applications, it is entirely up to the CPU's core to work, so in order for its advantages to fully play out, to avoid excessive thread context switching, the ideal scenario is: compute-intensive more ideal number of threads = CPU Core thread number +1.
For IO-intensive applications, read-write databases, read and write files all involve Io, and once IO occurs, the thread waits, and when the IO ends and the data is ready, the thread will continue to execute. Therefore, we can find that for IO-intensive applications, we can set up a number of threads in the thread pool, so that during the time of waiting for IO, the thread can do other things and improve the efficiency of concurrent processing. The more appropriate scenario is: IO-intensive applications Compare ideal threads = number of CPU kernel threads *2+1.
Android, Asynctask in the source code:


private static final int cpu_count = Runtime.getruntime (). Availableprocessors ();p rivate static final int core_pool_size = Cpu_count + 1;private static final int maximum_pool_size = Cpu_count * 2 + 1;public static final Executor Thread_pool_exe Cutor            = new Threadpoolexecutor (core_pool_size, Maximum_pool_size, keep_alive,                    timeunit.seconds, Spoolworkqueue, sthreadfactory);


The number of thread pools created between compute-intensive and IO-intensive is more common.

In Rxjava, a good control of thread pool creation is provided:

Scheduler Type effect
Schedulers.computation (?) Used for computing tasks such as event loops or callback processing, not for IO operations (use Schedulers.io () for IO operations); The default number of threads equals the number of processors
Schedulers.from (Executor) Using the specified executor as the scheduler
Schedulers.immediate (?) Start executing tasks immediately on the current thread
Schedulers.io (?) For IO-intensive tasks such as asynchronous blocking IO operations, the thread pool of this scheduler will grow as needed, and for normal computing tasks, use Schedulers.computation (); Schedulers.io (?) The default is a cachedthreadscheduler, much like a new thread scheduler for wired cache
Schedulers.newthread (?) Create a new thread for each task
Schedulers.trampoline (?) When the other queued tasks are completed, the current thread is queued to begin execution



Welcome to scan QR Code, follow the public number






Use of the Java thread pool

Related Article

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.