Interview questions

  1. Main thread pool parameters

Main parameters of the thread pool is: the core number of threads, the maximum number of threads, thread free survival time, thread free survival time unit, buffer queue, thread creation factory (default Executors. DefaultThreadFactory ()), rejection policies (the default AbortPolicy refused to strategy); ArrayBlockingQueue(bounded queue), LinkedBlockingDeque (unbounded queue),SynchronousQueue (which holds no data), and ArrayBlockingQueue(which holds no data). AllowCoreThreadTimeOut, which sets whether core threads have the same idle lifetime as non-core threads.

  1. The thread pool performs the process submission task and determines whether the number of threads exceeds the number of core threads. If the number of threads does not exceed the number of core threads, a new thread is created to execute the task; if the number exceeds the number of threads, it is added to the queue. If the queue is full, a new thread is created to process the task until the maximum number of threads is reached; If the maximum number of threads is reached, the reject policy is executed.

  2. Normally, a thread pool can be created and live until the main thread that created the pool or the entire program is no longer running. Unless the shutdown() or shutdownNow() methods of the thread pool are manually called, or an error occurs in the thread pool execution that directly causes the thread pool to fail to handle;

  3. How to keep a thread running in a thread pool, using a while method to loop through the queue to fetch tasks; With allowCoreThreadTimeOut not set: Threads within the core number of threads will use blocking to get the task from the queue (so the thread will always run and suspend). Threads after the core number of threads will use a timeout strategy to get the task from the queue. When there is no task in the queue, the current thread will break out of the while loop. The thread will be reclaimed), and continue to perform subsequent operations until the execution is complete; When allowCoreThreadTimeOut is set, all threads use timeout to retrieve tasks from the queue until there is only one valid thread in the pool.

  4. There are two ways to close a thread pool: shutdown() : stops receiving new tasks (Runnable), and the remaining tasks continue to execute. ShutdownNow () : Stops receiving tasks, does not process the tasks in the queue, and the executing thread will also be terminated;

  5. The question of how a thread pool can reclaim extra threads comes back to how a thread pool keeps threads running. When there are no more tasks in the thread pool queue, it exits the while loop in the runWorker, and finally enters the processWorkerExit method. When this method is finished, It means that the task of this thread is finished, which marks the completion of the execution of this thread; This method is to add the number of tasks executed by the original thread to the thread pool and remove the worker from the worker.

  6. How thread pools keep threads safe Almost all methods use ReentrantLock to keep threads safe; The thread pool instantiates the ReentrantLock, that is, all threads in a thread pool share the ReentrantLock lock; Another is that in addWorker method, cas is used in the first part to ensure the safety of repairing the number of threads in the thread pool, and ReentrantLock is used in the second part to ensure the safety of adding workers to the thread. Another is that in getTask, CAS is also used for concurrency control when threads are reclaimed in the case of concurrency (CAS operates on CTL).

  7. Several common thread pools, briefly

    • NewSingleThreadExecutor: Both the core thread and the maximum thread count are 1, use the LinkedBlockingQueue queue, and limit the size to integer.max_value, ensuring that they are executed in the specified order
    • NewFixedThreadPool: a thread pool with a fixed number of threads. The number of core threads is the same as the maximum number of threads. Also use LinkedBlockingQueue and limit the size to integer.max_value;
    • NewCachedThreadPool: Creates a thread pool with a core thread count of 0 and a maximum thread count of INTEger. MAX_VALUE, using SynchronousQueue, i.e., creating a new thread to process a task as it enters it;
    • NewScheduledThreadPool: is the underlying ScheduledThreadPoolExecutor, this class inherits the ThreadPoolExecutor, mainly carry out regular or periodic tasks;

    The following thread pools are created by Executors: * If the queue capacity is set to integer. MAX_VALUE, the maximum number of threads is set to *. Intege. MAX_VALUE, but it is not recommended to use Executors to create a thread pool. Instead, manually create ThreadPoolExecutor to avoid resource depletion.

  8. These exceptions are divided into two categories: one is the thread pool itself exceptions, basically are the thread pool to check some of its own properties and states and the parameters of the passed thread pool check and directly thrown exceptions; The other is the exception thrown during the execution of the incoming thread’s task.

    Here to say that the execution of the task error, here is also divided into two situations: 1. If the task is submitted using the execute method directly, then the runWorker method of ThreadPoolExecutor wraps the task execution with a try. AfterExecute (Task, thrown) is then called as an argument to the task and the exception thrown. By default, this method in the thread pool does nothing; If ThreadPoolExecutor submits a task using the AbstractExecutorService method, FutureTask should be used to encapsulate the task. A try is also used to wrap task execution errors, so that errors thrown by task execution cannot be caught in the ThreadPoolExecutor runworker.

    How do you handle exceptions? 1. Use a try catch in a task, but only within the task itself. 2. If you use the Submit task, use the Future get method to get the thrown exception; 3. Rewrite the afterExecute method in the thread pool to handle tasks and errors by itself;

  9. What’s the difference between execute and submit? Execute is ThreadPoolExecutor’s own method, which processes tasks directly and returns no value. Submit is an AbstractExecutorService method derived from ThreadPoolExecutor. This method encapsulates the task using FutureTask and then calls the execute method using the encapsulated task as an argument. And submit can return a value;

  10. If more than one thread in the thread pool fails to fetch tasks at the same time, will all the threads be reclaimed? No, because by default allowCoreThreadTimeOut is false. If this is done, the remaining threads will not meet the set number of core threads and allowCoreThreadTimeOut will have no effect. Why is it not recycled? In getTask’s method, CAS is used for concurrency control to ensure that only one thread will be successfully reclaimed in the case of multiple threads.

  11. What are the rejection strategies?

    • CallerRunsPolicy: Use the thread that called the thread pool (the original thread) to process the task
    • AbortPolicy: throw RejectedExecutionException error, this is the default thread pool refused to strategy
    • DiscardPolicy: do nothing, empty method, is to abandon the task;
    • DiscardOldestPolicy: Discards an old task in a queue and invokes the execute method. The task is not directly entered into a queue and processed by execute.

    The RejectedExecutionHandler interface needs to be implemented. The four rejection policies above are static classes defined in the ThreadPoolExecutor class;

The last

Continuously updated…

reference

  1. How to size thread pools properly
  2. Java Thread Pool Interview Questions (Concise)
  3. Java thread pool parsing
  4. 5 years of Java experience, summary of the interview of Byte, Meituan and Kuaishou core departments