"Java concurrent programming art" of the thread pool (a)

Thread pool Advantages:

  • Reduce resource overhead: each task does not require re-created and destroyed on arrival
  • Improve manageability: unified thread tuning, monitoring
  • The task of improving response time: no need to wait thread creation

Various parameters of the thread pool is created:

  • corePoolSize: a core number of threads. When the core is less than the number of threads, priority is also to create a full core number (even if there is a spare kernel thread) Thread
  • maximumPoolSize: maximum number of threads. When workQueue full, to create a new thread to perform new tasks
  • keepAliveTime: survival. Non-core thread can spare maximum time
  • workQueue: task blocking queue. When submitting a new task and the core number of threads have been used up, new tasks will be to join the task queue

Thread pool creation process:

  1. When you submit the task, first determine the core number of threads whether has been created , if not, first create a full core number of threads ; otherwise enter the next stage
  2. Determine whether the core number of threads that have all been occupied, if not the core thread to execute; on the contrary into the next stage
  3. Determine whether the work queue is full, if not full join the queue waiting; on the contrary into the next stage
  4. Determine the current number of threads is less than MaxThread, if so, the new thread is created to perform tasks; on the contrary policy RejectPolicyHandler perform the corresponding call

Create a thread pool

We can create a thread pool by ThreadPoolExecutor

ThreadPoolExecutor(
    int corePoolSize,
    int maximumPoolSize,
    long keepAliveTime,
    TimeUnit unit,
    BlockingQueue<Runnable> workQueue,
    RejectedExecutionHandler handler)

1) corePoolSize: When you submit a task (even if the other core is idle threads can perform new tasks), the thread pool creates a new thread to perform the task, until corePoolSize thread is created, it is no longer created. If you want to create additional, depends on the parameters back. If a thread calls a prestartAllCoreThreads()method to create and start the thread pool will advance all core threads

2) maximumPoolSize: The maximum number of threads in the thread pool can be created. If the queue is full, and the number of threads that have been created less than the maximum number of threads, the thread pool will re-create a new thread to perform the task. If the unbounded queue, this parameter is not effective

3) keepAliveTime: After the idle worker thread pool, to keep alive the time. If each thread execution time is shorter, this value can transfer large increase thread utilization

4) unit: unit of time

5) workQueue: to save the task of blocking queue waiting to be executed, you can select the following blocking queue:

* ArrayBlockingQueue: 是一个基于数组结构的有界阻塞队列,此队列按FIFO原则队元素进行排序
* LinkedBlockingQueue: 一个基于链表结构的阻塞,此队列按FIFO排序元素,吞吐量通常要高于ArrayBlockingQueue。静态工厂方法Executors.newFixedThreadPool()使用了这个队列。
* SynchronousQueue: 一个不存储元素的队列。每个插入操作要必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量通常要高于LinkedBlockingQueue,静态工厂方法Executors.newCachedThreadPool使用了这个队列
* PriorityQueue: 一个具有优先级的无限阻塞队列

6) handler: RejectPolicy default, there are four:
* AbortPolicy, direct throw an exception
* DiscardPolicy, discard the task, giving up processing
* CallerRunsPolicy, only the caller thread to perform tasks
* DiscardOldestPolicy, discard the head of the queue queue element

Mission

Submit the thread pool task There are two ways to submit tasks to the thread pool, respectively execute () and submit ():

  • execute: After performing no return value, can not determine whether the task was successfully executed thread pool
  • submit: After submitting returns an object of type Future, by the Future object can determine whether the execution was successful. Which can get method blocks the current thread until the task is completed, get (timeout, unit) method can be blocked for some time after the current thread returns

Close Thread

There are two ways to close the thread pool, respectively, shutdown()andshutdownNow()

Thing in common:
All threads traversing thread pool, and then one by one the calling thread interrupt()method to interrupt the thread, so I can not respond to the interrupted thread may never be terminated.

difference:

  • shutdownNow first state of the thread pool is set to STOP, and then try to stop all the threads being executed or suspend tasks, and returns a list of tasks awaiting execution
  • shutdown just the state of the thread pool is set to SHUTDOWN state, and then not being interrupted all threads mission

When any one of the shutdown method is invoked, isShutdown () method returns true. When all the tasks closed, call isTerminated () will return true.

Specifically to call shutdown()or shutdownNow()need to judge (usually call depending on the service shutdown()). If the task is not necessarily to be executed, you can useshutdownNow()

The rational allocation

  • Nature of the tasks: CPU-intensive tasks, IO-intensive tasks, the hybrid mission
  • Priority tasks: high, medium and low
  • Execution time of the task: long, medium and short
  • Dependent tasks: whether to rely on other system resources, such as database connection

How to choose:

  • CPU intensive tasks takes a long time to use CPU operations, the number of threads is preferably configured: N CPU +. 1
  • IO-intensive tasks not been occupied by the CPU, configure as many threads: 2 * N the CPU
  • If the task is a hybrid, try to split into CPU-intensive tasks and IO-intensive tasks
  • Dependent tasks database connection pool, because of the need to wait for the thread to submit SQL database returns the results, the longer the wait, the longer the CPU idle time, the greater the number of threads should be set, so as to make better use of CPU.

Note: It is recommended to use a bounded queue, because if the thread pool threads are blocked the work of the task squeeze in the thread pool will eventually cause the entire system unusable

Monitoring elements

  • taskCount: the number of tasks you need to perform thread pool
  • completedTaskCount: the number of tasks in the thread pool during operation has been completed, less than or equal taskCount
  • targetPoolSize: The maximum number of threads in the thread pool will have been created. You can ever pull a fast one until the thread pool by this data.
  • getPoolSize: the number of threads in the thread pool. If the thread pool is not destroyed, the thread pool thread will not automatically destroyed, so the value is only to rise
  • getActiveCount: the number of threads access activities

Monitored by extending the thread pool. You can customize the thread pool thread pool through inheritance, rewrite the thread pool beforeExecute(), afterExecute(), terminated()the method can also be executed before the task, to monitor the implementation of some code.

to sum up

This article is mainly to understand the meaning has been optimized when using the various elements of the thread pool, and monitoring.

Guess you like

Origin www.cnblogs.com/codeleven/p/10963128.html