Java thread pool summary

I What is a thread pool?

Thread pool: create several executable threads and put them into a pool (container). When a task needs to be processed, it will be submitted to the task queue in the thread pool. After processing, the thread will not be destroyed, but still wait for the next task in the thread pool.

II Why use thread pools?

Because creating a thread in Java requires calling the API of the operating system kernel, and the operating system allocates a series of resources to the thread, the cost is very high. Therefore, the thread is a heavyweight object, and frequent creation and destruction should be avoided.
Using thread pools is a good way to avoid frequent creation and destruction.
Advantages of thread pool:

  1. Reduce resource destruction: reduce the consumption caused by thread creation and destruction by reusing the created threads.
  2. Improve response speed: when the task arrives, the task can be executed immediately without waiting for the thread to be created.
  3. Prevent server overload: memory overflow or CPU exhaustion
  4. Improve the manageability of threads: threads are scarce resources. If they are created without restrictions, they will not only consume resources, but also reduce the stability of the system. Using thread pool can carry out unified allocation, tuning and monitoring.

III Create thread pool

Several common thread pool types:

  1. newCachedThreadPool: create a cacheable thread pool. If the length of the thread pool exceeds the processing needs, you can flexibly recycle idle threads. If there is no recyclable thread, you can create a new thread.
  public static void main(String[] args) throws Exception {
    	ExecutorService pool = Executors.newCachedThreadPool();//Create thread pool
    	
    	for(int i =0;i<10;i++) {
    		Thread.sleep(200);
    		pool.execute(()->{//Thread pool create thread
    			for(int s =0;s<10;s++) {
    				System.out.println(Thread.currentThread().getName()+":"+s);
    				try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}
    		});
    	}
	}

result:

  1. newFixedThreadPool: create a fixed length thread pool to control the maximum concurrent number of threads. The exceeded threads will wait in the queue.
 public static void main(String[] args) throws Exception {
    	ExecutorService pool = Executors.newFixedThreadPool(2);//Create a thread pool with a fixed length of 2
    	
    	for(int i =0;i<10;i++) {
    		Thread.sleep(200);
    		pool.execute(()->{//Thread pool create thread
    			for(int s =0;s<10;s++) {
    				System.out.println(Thread.currentThread().getName()+":"+s);
    				try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}
    		});
    	}
	}

result:

  1. newScheduledThreadPool: create a fixed length thread pool to support scheduled and periodic task execution.
 public static void main(String[] args) throws Exception {
    	ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);//Create a route pool with a fixed length of 5
    	int t =0;
    	pool.scheduleAtFixedRate(()->//Scheduled thread creation
    	 System.out.println(Thread.currentThread().getName()+":"+t)
    	, 0, 2, TimeUnit.SECONDS);
    	
	}

result:

4. Newsinglethreadexecution: create a singleton thread pool, which will only use a unique working thread to execute tasks, and ensure that all tasks are executed in the specified order (FIFO, LIFO, priority)

public static void main(String[] args) throws Exception {
    	ExecutorService pool = Executors.newSingleThreadExecutor();//Create thread pool
    	
    	for(int i =0;i<10;i++) {
    		Thread.sleep(200);
    		pool.execute(()->{//Thread pool create thread
    			for(int s =0;s<10;s++) {
    				System.out.println(Thread.currentThread().getName()+":"+s);
    				try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}
    		});
    	}
	}

result:

IV Thread pool configuration parameters

  1. corePoolSiz: the number of core threads in the thread pool. When it is not used, it will not be recycled.
  2. Maximum pool: is the maximum number of threads that can be held in the thread pool
  3. keepAliveTi: the longest time that can be reserved in the thread pool except for the core thread, because in the thread pool, except that the core thread cannot be cleared even when there is no task, the rest have survival time, which means the longest idle time that can be reserved by non core threads
  4. util: a unit of time
  5. workQueue: it is the waiting queue. Tasks can be stored in the task queue for execution. The FIFO principle (first in first out) is implemented
  6. handler: reject policy

V Thread pool process, rejection policy and submission method

5.1 line process

5.2 thread pool rejection policy

When the task queue is full, if any tasks are submitted, the reject policy will be triggered

1.AbortPolicy: throw an exception directly without executing a new task, indicating that the thread pool is full. This method is the default.
2.CallerRunsPolicy: directly call execute to execute the current task.
3.DiscardPolicy: discard the task without throwing an exception.
4.DiscardOldestPolicy: discard the oldest task in the task queue, that is, the one first added to the queue, and then add the new task. First pop up the first task from the task queue, leave a place, and then execute the execute method again to add the task to the queue.

5.3 thread pool submission method

Vi Thread pool related issues

1. Set the number of core threads in the thread pool?

(1) The thread count concept of CPU is only useful for Intel CPUs because it is implemented through Intel hyper threading technology.
(2) If there is no hyper threading technology, a CPU core corresponds to a thread. Therefore, for AMD CPU, there is only the concept of core number, not the concept of thread number.
2. How to use thread pool for businesses with high concurrency and short task execution time?
For businesses with high concurrency and short task execution time, the number of threads in the thread pool can be set to the number of CPU cores + 1 to reduce the switching of thread context
3. How to use thread pool for businesses with low concurrency and long task execution time?
If the business time is long, focus on IO operations, that is, IO intensive tasks, because IO operations do not occupy CPU, so don't let all CPUs idle. You can appropriately increase the number of threads in the thread pool and let the CPU handle more business.
If the business takes a long time and focuses on computing operations, that is, computing intensive tasks, the number of threads in the thread pool is set less to reduce the switching of thread context

Keywords: Java Multithreading thread pool

Added by barbs75 on Wed, 12 Jan 2022 11:07:18 +0200