Thread pool concept

Our last article looked at ThreadPoolExecutor, and if I had to say one thing about its main advantage, it’s thread replacement. And Executors tools, greatly simplifies the work of research and development personnel.

Let me repeat the thread pool concept with a diagram. Production-consume more model.

  • The producer drops the thread task into the thread pool, and the producer is finished.
  • The thread pool controls consumer consumption elements, which can be one or more, depending on the thread pool parameters corePoolSize and maxPoolSize Settings.
  • Blocking queues are used to hold thread tasks thrown in by producers, such as ArrayBlockingQueue, LinkedBlockingQueue, DelayedQueue, etc. The thread pool will be saturated if the producer is producing more than the consumer can consume, if the blocking queue has a limit of length and exceeds the queue length, and if the queue has no limit of length, the thread pool can also be OOM, because the thread task may run out of memory.

See my previous article thread Pool Interview Questions for a more detailed concept.

Timing task delay principle

Remember that blocking queue we talked about above? The bottom layer of the timed task thread pool is implemented using DelayedQueue, which has one of the biggest characteristics: queue on time, everyone has taken the driver’s license, there are always four people in the bus during the exam of subject 3, assuming that it takes 15 minutes for one person to take the exam, then the exam student queue looks like this.

The bottom layer of DelayedQueue needs to implement Delayed interface, which needs to implement getDelay method and compareTo method at the same time. GetDelay method is used to calculate the queue time, and once it is less than 0, it will be out of the queue. The compareTo method is used to sort by minimum to maximum trigger time. This is how Schedule thread pool task delay works. If you need a sample code, please refer to my article “Concurrent Queues: Use of PriorityBlockingQueue and DelayQueue”.

ScheduleWithFixedDelay differs from scheduleAtFixedRate

According to the figure above, assume that a thread task takes 1 second and is scheduled to be executed in 3 seconds. ScheduleWithFixedDelay is actually executed once every 4 seconds.

  • ScheduleWithFixedDelay: This parameter is executed at the end time of a task.

  • ScheduleAtFixedRate: Runs at a fixed period.

FutureTask retrieves the return value

In ScheduledThreadPoolExecutor, ScheduledFutureTask the return value is to obtain regular task, FutureTask inheritance. Let’s look at a simplified flowchart for FutureTask call GET blocking.

  1. Tasks are added to the thread pool, encapsulated as ScheduledFutureTask, and the Callable interface is implemented to retrieve the task return value.
  2. When a client thread retrieves the return value of a pool thread’s execution via GET, the client thread blocks until the pool thread completes its task.

In practice, we usually use the return value to test multithreading performance.

The Timer is

  1. The Timer is single-threaded and does not return a value. ScheduledThreadPoolExecutor is multithreaded, USES the thread reuse instead of creating a new thread, and FutureTask return values.

  2. The Timer thread calls sche method, if TimerTask anomaly, the Timer single-threaded hang out directly, and ScheduledThreadPoolExecutor catches the exception, thread does not affect other consumers. Here’s the code test.

    import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit;

    / * *

    • @ the author: jiaolian
    • @date :Created in 2021-02-25 13:50
    • Description: The Timer thread exits because the Timer task is abnormal.
    • @ modified By:
    • Public account: Call Lian

    */ public class TimerTaskExceptionTest {

    public static void main(String[] args) throws InterruptedException { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("first_task"); }}, 0100, 0); TimeUnit.SECONDS.sleep(3); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("second_task"); int x = 5/0; }}, 0100, 0); }Copy the code

    }

Timer submits first_task and second_task. After 3 seconds, second_task executes 5/0, and the timer thread exits. If change ScheduledThreadPoolExecutor first_task would not be affected. In practice, it is recommended to use the method in the scheduled task thread pool to process tasks.

conclusion

Today we introduced several important aspects of the interview in the thread pool pilot, sort out the hope can help you, write than incomplete, at the same time there are many places that need to be corrected, I hope the pro to point out and comment, like please like and pay attention to oh. Point attention, do not get lost, I am called practice [public account], micro signal ** [jiaolian123ABC] ** while calling while practicing.