Java Concurrent Programming -- use and analysis of four thread pools

Posted by wgordonw1 on Wed, 15 Dec 2021 00:31:59 +0100

Execute an asynchronous task. Are you still just a new Thread?
Then you have too many out. The disadvantages of new Thread are as follows:

a. The performance of each new Thread to create a new object is poor.

b. Threads lack unified management, may create new threads without restrictions, compete with each other, and may occupy too many system resources, resulting in panic or oom.

c. Lack of more functions, such as timed execution, periodic execution, thread interrupt.

Use the thread pool, boy

Compared with new Thread, Java provides the benefits of four thread pools

a. Reusing existing threads reduces the overhead of object creation and extinction, and has good performance.

b. It can effectively control the maximum number of concurrent threads, improve the utilization of system resources, and avoid excessive resource competition and congestion.

c. It provides functions such as regular execution, regular execution, single thread, concurrency control, etc.

Four thread pools provided by Java

  1. newFixedThreadPool
    Create a fixed length thread pool to control the maximum concurrent number of threads. The exceeded threads will wait in the queue.
  2. newSingleThreadExecutor
    Create a singleton thread pool. It will only use a unique worker thread to execute tasks to ensure that all tasks are executed in the specified order (FIFO, LIFO, priority).
  3. 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.
  4. newScheduledThreadPool
    Create a fixed length routing pool to support regular and periodic task execution.

After understanding, let's use it
Code example:

1.newFixedThreadPool

Create a fixed length thread pool to control the maximum concurrent number of threads. The exceeded threads will wait in the queue.

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {

@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

Because the thread pool size is 3, and the sleep is 2 seconds after each task outputs index, three numbers are printed every two seconds.
The size of the fixed length route pool is best set according to the system resources. Such as runtime getRuntime(). availableProcessors(). Please refer to PreloadDataCache.

2.newSingleThreadExecutor

Create a singleton thread pool. It will only use a unique worker thread to execute tasks to ensure that all tasks are executed in the specified order (FIFO, LIFO, priority).

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {

@Override
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

The results are output in sequence, which is equivalent to executing each task in sequence.

3.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.

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

cachedThreadPool.execute(new Runnable() {

@Override
public void run() {
System.out.println(index);
}
});
}

The thread pool is infinite. When the second task is executed, the first task has been completed, and the thread executing the first task will be reused instead of creating a new thread each time.

4.newScheduledThreadPool

Create a fixed length routing pool to support regular and periodic task execution.
The example code of delayed execution is as follows:

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {

@Override
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);

Indicates a delay of 3 seconds.

Regular execution example code is as follows:

scheduledThreadPool.scheduleAtFixedRate(new Runnable() {

@Override
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds");
}
}, 1, 3, TimeUnit.SECONDS);

Indicates that it is executed every 3 seconds after a delay of 1 second.

analysis

How can light be used? We have to go in and see its principle:
Click on the method to create a fixed thread pool,

It turned out that a method was called to pass in the number of threads as a parameter
Take another look, and then click in the cache thread pool

This method is called again. It seems that ThreadPoolExecutor() is the real method to create thread pool. Let's click this method again
Open Structure and see that this method has four overloads and different parameters passed

Here is what the parameters mean for your reference

public ThreadPoo1Executor(
int corePool size,//Number of core threads
int maximumPoolsize,/Maximum number of threads
long keepAliveTime,//Timeout, the free survival time of threads beyond the number of core threads
Timeunit unit,//Survival time unit
BlockingQueue<Runnable> workQueue,//Save the queue that executes the task
ThreadFactory threadFactory,//Create the factory used by the new thread
RejectedExecutionHandler handler//Processing method when the task cannot be executed
)

Here, let's pay attention to these two parameters

int corePool size,//Number of core threads
int maximumPoolsize,/Maximum number of threads

In fact, this is the difference between established and temporary workers. What does it mean
That is, if our company is in a hurry for a project and there are not enough people, what should we do? Enrollment expansion? But we usually don't need so many people. Then we can find an outsourcing company to recruit some outsourcing personnel. We can borrow them temporarily and return them when the project is completed.
That is, the part between the core and the maximum is variable, there is when it is needed, and there is no when it is not needed.

Topics: Java thread pool