The basic idea of thread pool is still a kind of idea of object pooling

Source: Internet
Author: User
Tags terminates

The basic idea of the thread pool is also the idea of an object pool, which opens up a memory space in which many (not dead) threads are stored, and the thread execution schedule is handled by the pool Manager. When a thread task is taken from a pool, the Threads object is pooled after execution, which avoids the performance overhead of repeatedly creating thread objects and saves system Resources.

For example: an application to work with the network, there are many steps need to access the network, in order not to block the main thread, each step to create threads, in-line and network interaction, with the thread pool is simple, the thread pool is a package of threads, make the thread easier to use, only need to create one thread pool, Put these steps into a thread pool like a task, as long as you call the Destroy function of the thread pool when the program is Destroyed.


There are three thread pools commonly used in Java:
    • Newfixedthreadpool
Create a thread pool that reuses the number of fixed threads and run them in a shared, unbounded Queue. At any point, most nthreads threads are in the active state of the processing Task. If additional tasks are committed while all threads are active, the additional task waits in the queue until there are available THREADS. If any thread terminates due to a failure during execution prior to shutdown, a new thread will perform subsequent tasks (if Necessary) instead of it. A thread in the pool will persist until a thread is explicitly closed.
Executorservice pool = Executors.newfixedthreadpool (2);
//created implements the Runnable interface object, the thread object of course also implements the Runnable interface
Thread t1 = new MyThread ();
Thread t2 = new MyThread ();
Thread t3 = new MyThread ();
Thread t4 = new MyThread ();
Thread T5 = new MyThread ();
//put the thread into the pool for execution
Pool.execute (t1);
Pool.execute (t2);
Pool.execute (t3);
Pool.execute (t4);
Pool.execute (t5);

    • Newsinglethreadexecutor
Create a Executor that uses a single worker thread to run the thread in a unbounded Queue. (note that if this single thread is terminated because of a failure during the execution of the shutdown, a new thread will replace it for subsequent tasks if needed). Each task is guaranteed to be executed sequentially, and no more than one thread is active at any given Time. Unlike other equivalent Newfixedthreadpool (1), it is guaranteed to use other threads without reconfiguring the executing program returned by this Method.
    • Newcachedthreadpool

Create a thread pool that can create new threads as needed, but reuse them when previously constructed threads are Available. For programs that perform many short-term asynchronous tasks, these thread pools can often improve program performance. Calling execute reuses the previously constructed thread, if the thread is Available. If an existing thread is not available, a new thread is created and added to the Pool. Terminates and removes from the cache those threads that have not been used for 60 seconds. therefore, a thread pool that remains idle for a long time does not use any Resources. Note that you can use the Threadpoolexecutor construction method to create a thread pool with similar attributes but with different details, such as time-out Parameters.


The following is the content of the Reprint:

Threadpoolexecutor (int corepoolsize, int Maximumpoolsize,long keepalivetime,

Timeunit Unit,blockingqueue<runnable>workqueue,rejectedexecutionhandler Handler)

Corepoolsize: thread Pool maintains a minimum number of threads maximumpoolsize: Maximum number of threads maintained by the thread pool keepalivetime: idle time allowed by thread pool maintenance threads

Unit: The thread pool maintains the units of idle time allowed by threads workQueue: buffer queue used by handler: thread pool processing policy for rejected tasks

A task is added to the thread pool by the Execute (Runnable) method, the task is an object of type Runnable, and the task is executed by the run () method of the Runnable type Object.

When a task is added to the thread pool by the Execute (Runnable) method:

If the number in the thread pool is less than corepoolsize at this point, even if the threads in the thread pool are idle, create a new thread to handle the task being Added.

2 If the number in the thread pool is equal to corepoolsize, but the buffer queue Workqueue is not full, then the task is placed in the buffer Queue.

3 If the number of threads in the thread pool is greater than corepoolsize, the buffer queue Workqueue full, and the number of thread pools is less than maximumpoolsize, a new thread is built to handle the task being Added.

4 If the number of threads in the thread pool is greater than corepoolsize, the buffer queue is Workqueue full, and the number in the thread pool equals maximumpoolsize, The task is handled by handler the policy Specified. That is: the priority of the processing Task Is: core thread corepoolsize, task queue workqueue, maximum thread maximumpoolsize, If all three are full, use handler to handle the rejected Task.

5 when the number of threads in the thread pool is greater than corepoolsize, if a thread is idle for more than keepalivetime, the thread is Terminated. This allows the thread pool to dynamically adjust the number of threads in the Pool.

A executorservice that uses a number of possible pool threads to perform each submitted task, typically using the Executors factory method Configuration.

The thread pool resolves two different issues: because of the reduced overhead of each task invocation, they typically provide enhanced performance when performing a large number of asynchronous tasks, and can also provide methods for binding and managing resources, including the threads that are used to perform collection tasks. Each threadpoolexecutor also maintains some basic statistical data, such as the number of completed Tasks.

For ease of use across a large number of contexts, This class provides a number of adjustable parameters and extension hooks. however, programmers are strongly advised to use the more convenient executors factory method Executors.newcachedthreadpool () (without a boundary pool, which can be used for automatic thread recycling), executors.newfixedthreadpool ( Int) (fixed-size thread Pool) and executors.newsinglethreadexecutor () (single background thread), which have predefined settings for most usage scenarios. otherwise, When you manually configure and adjust this class, use the following guidelines:

Core and Maximum pool size

The threadpoolexecutor will automatically adjust the pool size based on the boundaries set by Corepoolsize (see getcorepoolsize ()) and maximumpoolsize (see getmaximumpoolsize ()). When a new task is committed in method execute (java.lang.Runnable), if the running thread is less than corepoolsize, a new thread is created to process the request, even if the other worker threads are Idle. If you run more threads than corepoolsize and less than maximumpoolsize, a new thread is created only when the queue is Full. If you set the same corepoolsize and maximumpoolsize, a fixed-size thread pool is Created. If you set Maximumpoolsize to a basic unbounded value (such as integer.max_value), the pool is allowed to accommodate any number of concurrent tasks. In most cases, the core and maximum pool sizes are only set on a construction basis, but they can also be changed dynamically using Setcorepoolsize (int) and Setmaximumpoolsize (int).

On-demand Construction

By default, the core thread can be dynamically overridden with method Prestartcorethread () or prestartallcorethreads (), even if it was originally created and started only when a new task is Needed.

Create a new thread

Create a new thread using Threadfactory. If not otherwise stated, threads are created in the same threadgroup using Executors.defaultthreadfactory (), and these threads have the same norm_priority priority and Non-daemon Status. By providing different threadfactory, you can change the name of the thread, the thread group, the priority, the daemon state, and so On. If threadfactory fails to create a thread when returning null from newthread, the executor continues to run, but cannot perform any tasks.

Keep Active Time

If there are currently more than corepoolsize threads in the pool, these extra threads will terminate when the idle time exceeds KeepAliveTime (see getkeepalivetime (java.util.concurrent.TimeUnit)). This provides a way to reduce resource consumption when the pool is Inactive. If the pool becomes more active later, you can create a new thread. You can also use method Setkeepalivetime (long, java.util.concurrent.TimeUnit) to dynamically change this parameter. Use the value of Long.max_value timeunit.nanoseconds to effectively disable idle threads from the previous termination state before Closing.

Queuing

All blockingqueue can be used to transfer and maintain submitted tasks. You can use this queue to interact with the pool size:

A. If you run fewer threads than corepoolsize, Executor always prefers to add new threads without queuing.

B. if the thread running is equal to or more than corepoolsize, Executor always prefers to join the request to the queue without adding a new thread.

C. If the request cannot be queued, a new thread is created unless the thread is created beyond maximumpoolsize, in which case the task is Rejected.

There are three common strategies for queuing:

Submit Directly. The default option for the work queue is synchronousqueue, which will submit tasks directly to the thread without maintaining Them. here, If there is no thread available to run the task immediately, attempting to join the task to the queue will fail, and a new thread will be Constructed. This policy avoids locking when processing a collection of requests that may have internal dependencies. Direct submissions typically require unbounded maximumpoolsizes to avoid rejecting newly submitted tasks. This policy allows the possibility of an increase in the number of lines that are allowed to continue when the command arrives in a row that exceeds the average that the queue can Handle.

Unbounded Queues. Using unbounded queues (for example, linkedblockingqueue that do not have a predefined capacity) causes new tasks to be queued when all corepoolsize threads are Busy. This way, the created thread will not exceed Corepoolsize. (therefore, the value of the maximumpoolsize is not valid.) When each task is completely independent of other tasks, that is, when task execution does not affect each other, it is appropriate to use a unbounded queue, for example, in a Web page server. This queueing can be used to handle transient burst requests, which allow the possibility of an increase in the number of lines that are allowed to occur when the command reaches an average of more than the queue can Handle.

Bounded Queues. When using limited maximumpoolsizes, bounded queues (such as Arrayblockingqueue) help prevent resource exhaustion, but may be difficult to adjust and control. The queue size and maximum pool size may need to be compromised: using large queues and small pools minimizes CPU usage, operating system resources, and context switching overhead, but can result in artificially reduced throughput. If tasks are frequently blocked (for example, if they are I/O boundaries), the system may schedule more threads than you permit. Using small queues typically requires a large pool size, high CPU utilization, but may encounter unacceptable scheduling overhead, which also reduces throughput.

Rejected tasks

New tasks submitted in method execute (java.lang.Runnable) are rejected when Executor is closed and Executor uses a limited boundary for the maximum thread and work queue capacity and is already saturated. In both of these cases, the Execute method calls its Rejectedexecutionhandler rejectedexecutionhandler.rejectedexecution (java.lang.Runnable, Java.util.concurrent.ThreadPoolExecutor) Method. The following four predefined handler policies are available:

A. In the default threadpoolexecutor.abortpolicy, the handler is rejected and the runtime rejectedexecutionexception is Thrown.

B. in threadpoolexecutor.callerrunspolicy, the thread invokes the execute itself that runs the Task. This strategy provides a simple feedback control mechanism that can slow down the submission of new tasks.

C. In threadpoolexecutor.discardpolicy, the tasks that cannot be performed are Deleted.

D. in threadpoolexecutor.discardoldestpolicy, If the execution program has not been closed, the task at the head of the work queue is deleted, and then the execution of the program is retried (repeat this process if it fails again).

It is also possible to define and use other kinds of rejectedexecutionhandler classes, but doing so requires great care, especially when the policy is used only for specific capacity or queueing Policies.

Hook method

This class provides protected overridable BeforeExecute (java.lang.Thread, Java.lang.Runnable) and AfterExecute (java.lang.Runnable, Java.lang.Throwable) method, which is called before and after each task is Executed. They can be used to manipulate the execution environment, for example, reinitialize ThreadLocal, collect statistics, or add log entries. In addition, you can override method terminated () to perform all special processing that needs to be done after the Executor is completely terminated.

If the hook or callback method throws an exception, the internal worker thread fails sequentially and terminates abruptly.

Queue Maintenance

Method Getqueue () allows access to the work queue for monitoring and debugging Purposes. Strongly oppose the use of this method for any other purpose. Both the Remove (java.lang.Runnable) and purge () methods can be used to help with storage reclamation when a large number of queued tasks are Canceled.





From for Notes (Wiz)

The basic idea of thread pool is still a kind of idea of object pooling

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.