Thread Pool ThreadPoolExecutor, threadpoolexecutor

Source: Internet
Author: User

Thread Pool ThreadPoolExecutor, threadpoolexecutor

The school started in February March 5. I stayed at school for a few days and was bored. I don't know what to write. Just write something in the thread pool.

(1) role of the thread pool

The thread pool has two functions:

1. reduces the number of threads created and destroyed. Each worker thread can be reused to execute multiple tasks.

2. You can adjust the data of the worker threads in the thread pool based on the system's capacity to prevent server crashes due to excessive memory consumption.

To use a thread pool, you must manually or automatically set the number of threads based on the system environment. Less efficient system operation, more crowded system, and more memory occupied. The number of threads is controlled by the thread pool, and other threads are waiting in queue. After a task is executed, the task starts from the top of the queue. If the task is not waiting for the task, the thread pool resource is waiting. When a new task needs to run, if there is a waiting working thread in the thread pool, it can start to run; otherwise, it enters the waiting queue.

 

(2) Thread Pool Class Structure

1. The top-level interface is Executor. However, in strict sense, Executor is not a thread pool but a mechanism for running tasks.

2. ExecutorService can be considered as a real thread pool interface. The interface provides a method for managing the thread pool.

3. Executors is a tool class for threads. You can use Executors to create a thread pool.

However, the naming rules of Alibaba include:

[Force] The Thread Pool cannot be created using Executors, but through
ThreadPoolExecutor.
The processing method allows the writing staff to clarify the running rules of the thread pool and avoid the risk of resource depletion.
Note: the drawbacks of the thread pool object returned by Executors are as follows:
1) FixedThreadPool and SingleThreadPool:
The allowed Request queue length is Integer. MAX_VALUE, which may pile up a large number of requests, resulting in OOM.
2) CachedThreadPool and ScheduledThreadPool:
The number of threads allowed to be created is Integer. MAX_VALUE. A large number of threads may be created, resulting in OOM.

 

(3) Seven Core parameters of ThreadPoolExecutor
1 public ThreadPoolExecutor(int corePoolSize,2                           int maximumPoolSize,3                           long keepAliveTime,4                           TimeUnit unit,5                           BlockingQueue<Runnable> workQueue,6                           ThreadFactory threadFactory,7                           RejectedExecutionHandler handler) 

1. corePoolSize

The size of the core pool. After the thread pool is created,By default, there is no thread in the thread pool, but a thread is created to execute the task only after a task arrives.. By default, after a thread pool is created, the number of threads in the thread pool is 0. When a task arrives, a thread is created to execute the task.

2. maximumPoolSize

Maximum number of threads allowed in the pool. This parameter indicates the maximum number of threads that can be created in the thread pool. When the number of tasks is larger than corePoolSize, the task is added to workQueue. When the workQueue is full, the thread will be created to process the task. maximumPoolSize indicates that the wordQueue is full and the maximum number of threads can be created in the thread pool.

3. keepAliveTime

This parameter takes effect only when the number of threads in the thread pool is greater than corePoolSize.. When the number of threads is greater than corePoolSize, the maximum time for Idle threads to wait for a new task before termination

4. unit

KeepAliveTime time unit

5. workQueue

The thread that stores more than corePoolSize is waiting in this queue.

6. threadFactory

The factory used by the execution program to create a new thread

7. handler

The processing program used when the execution is blocked because it exceeds the thread range and queue capacity

 

(4) code Cases
 1 package com.test; 2  3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.LinkedBlockingQueue; 5 import java.util.concurrent.ThreadPoolExecutor; 6 import java.util.concurrent.TimeUnit; 7  8 /** 9     author  wenbochang10     public ThreadPoolExecutor(int corePoolSize,11                               int maximumPoolSize,12                               long keepAliveTime,13                               TimeUnit unit,14                               BlockingQueue<Runnable> workQueue) {15         this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,16              Executors.defaultThreadFactory(), defaultHandler);17     }18  */19 public class ThreadPoolTest {20     public static void main(String[] args) {21         22         ExecutorService executorService = 23                 new ThreadPoolExecutor(24                 5, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024));25         for (int i = 0; i < 10; i++) {26             executorService.execute(new MyTask());27         }28         System.out.println(executorService);29         executorService.shutdown();30     }31 }32 33 class MyTask implements Runnable{34 35     @Override36     public void run() {37         38         System.out.println("Thread name : " + Thread.currentThread().getName());39     }40 }

You can adjust the values of corePoolSize maximumPoolSize workQueue.

We can have a deeper understanding of the meaning of these three parameters.

I did not find the disadvantage of creating a thread by using Executors. However, I read an article in zhihu, which said that the cpu usage soared due to the unbounded queue of Executors. newCachedThreadPool. So we should use ThreadPoolExecutor to create a thread.

 

Ps. I wrote articles to deepen my memory and communicate with you (I don't guarantee that 100% is original to myself, because I will also find materials during the writing process ).

If you do not like the articles I wrote, just drop them silently. Don't spray me. Thank you for your progress.

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.