The thread pool in Java

Source: Internet
Author: User

The thread pool in Java

The benefits of a thread pool

1. Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the threads that have been created.

2. Improve response speed. When a task arrives, the task can be executed without the need to wait for the thread to be created.

3. Improve the manageability of threads. Threads are scarce resources that, if created indefinitely, not only consume system resources, but also reduce system stability, using a thread pool for uniform allocation, tuning, and monitoring.

Ii. types of thread pools

Java provides four thread pools via executors

1. Newcachedthreadpool creates a cacheable thread pool that is flexible to reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.

2. Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.

3. Newscheduledthreadpool creates a fixed-length pool that supports timed and recurring task execution.

4. 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).

Third, Threadpoolexecutor

1. The thread pools in each of the four Java threads are implemented using Threadpoolexecutor

2. Threadpoolexecutor (int corepoolsize, int maximumpoolsize, long keepalivetime, timeunit unit, blockingqueue< Runnable> workQueue)

3. Threadpoolexecutor inherits the Abstractexecutorservice abstract class, Abstractexecutorservice implements the Executorservice interface, Executorservice inherits the Executor interface

      • Corepoolsize: The size of the core pool, by default, after the thread pool has been created, the number of threads is 0, and when a task comes, a thread is created to perform the task, and when the thread pool threads reach Corepoolsize, the task is placed in the task cache queue.
      • Maximumpoolsize: The maximum number of threads that are created in a thread pool.
      • Keeplivetime: When a thread does not have a task to execute, the maximum time to save is terminated by default, and Keeplivetime only works until the number of threads in the thread pool >corepoolsize, until the thread count is not greater than corepoolsize.
      • WorkQueue: Blocking queue to hold tasks waiting to be executed
      • Threadfactory: Thread factory, used to create threads.

4. Threadpoolexecutor inherits the Abstractexecutorservice abstract class, Abstractexecutorservice implements the Executorservice interface, Executorservice inherits the Executor interface

  

Four, thread pool life cycle/state transition process

1. RUNNING: When the thread pool is created, the first knowledge is the RUNNING state, can accept the newly submitted task, and can also handle the tasks in the blocking queue;

2. SHUTDOWN: Off state, no longer accepting newly submitted tasks, but can continue to handle saved tasks in the blocking queue. When the thread pool is in the RUNNING state, calling the shutdown () method causes the thread pool to enter that state. (The Finalize () method also calls the shutdown () method to enter the state during execution);

3. STOP: Unable to accept new tasks or handle tasks in the queue, it interrupts the thread that is processing the task. When the thread pool is in the RUNNING or SHUTDOWN state, calling the Shutdownnow () method causes the thread pool to enter that state;

4. Tidying: If all tasks are terminated, Workercount (number of active threads) is 0, the thread pool enters the state and calls the terminated () method to enter the terminated state.

V. Composition of thread pool

1. Thread pool Manager: Used to create and manage thread pools

2. Worker threads: Threads in a thread pool

3. Task interface: the interface that each task must implement for the worker thread to dispatch its run

4. Task queue: For storing pending tasks, providing a buffering mechanism

Vi. Execute method Execution process

1. The main work of the Addworker method is to create a new thread in the threads pool and execute it, and the Firsttask parameter is used to specify the first task to be performed by the new thread, and the core parameter is true to determine whether the current number of active threads is less than corepoolsize when a new thread is added , false indicates whether the current active thread count is less than maximumpoolsize before a new thread is added

2. Add the following to the worker thread and execute, call is Addworker ()

3. The Submit method can get the return value after the thread executes, or the Execute method is called at the bottom

4. Execute Method Workflow

      • If the number of threads in the current thread pool is <corepoolsize, a thread is created for each task to execute, even if the thread is now idle.
      • If the number of threads in the current thread pool is >=corepoolsize, an attempt is made to add the task to the task cache queue, and if the addition succeeds, the task waits for the idle thread to take it out and, if the addition fails, attempts to create a thread to perform the task.
      • If the number of threads in the current thread pool is >= maximumpoolsize, there are 4 rejection policies,

1) AbortPolicy Discard task, throw rejectedexecutionexception

2) Discardpolicy refuse to execute, do not throw exception

3) Discardoldestpolicy discards the oldest task in the task cache queue and attempts to resubmit the new task

4) The Callerrunspolicy has a feedback mechanism that slows down the task submission.

Vii. work threads throughout the work flow

1. When the line Chengchigang is created, there is no thread inside. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool does not execute them immediately.

2. When the Execute ()/submit () method is called to add a task, the number of threads is judged (the thread pool creates the thread as a worker worker) and executes Addworker () to add and execute the task

3. Call the Runworker () method in Addworker () to perform the task Firsttask,firsttask after execution completes, get the waiting task from the blocking queue through the Gettask method, if there are no tasks in the queue, The Gettask method is blocked and suspended, and does not consume CPU resources;

4. When a thread has nothing to do, more than a certain amount of time (KeepAliveTime), the thread pool will determine if the number of threads currently running is greater than corepoolsize, then the threads will be stopped. So when all the thread pool tasks are completed, it eventually shrinks to the size of the corepoolsize.

The thread pool in Java

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.