How do I handle the concurrency of the thread pool?

Source: Internet
Author: User

"Foreword" We have been involved in the development of Android since the beginning of the process of processing time-consuming tasks to do in the non-UI thread. So we have a variety of programming methods for dealing with concurrency, whether it's a new thread of work (worker thread), or an Android-provided API (Asnytask, Runnable). Cursorlaoder, etc.) is a solution for time-consuming tasks. But in a large application, if we need to deal with a lot of heavy and frequent time-consuming tasks, if we use the previous means, it will undoubtedly bring a lot of inconvenience, a frequent creation of the destruction of the thread will cause resources (memory and CPU) waste, and the code will appear very messy. So we proposed using a thread pool to handle frequent time-consuming tasks.

In the JDK1.5 class library, Java developers provide us with a ready-made thread pool, and the API for the thread pool is provided under the Java.util.concurrent package.

My application architecture design, in the processing of concurrent tasks, it is necessary to use the thread pool, about the thread pool, I think of it as a unified management of multi-threaded tasks, specifically, the thread pool to accept multi-threaded tasks (implement Runnable interface), and by creating a thread pool with some parameters configured to manage and perform these tasks uniformly, we only need to send a message to the thread pool (the time-consuming operation we want to do) when we have to perform time-consuming tasks, and, of course, we can pass in some callback interfaces while sending the request. This will give you a callback to update the UI after the time-consuming task has finished executing.

How do I implement a custom thread pool?

While the thread pool provided by the JDK can meet general development requirements, it is still necessary to implement a custom thread pool.

Custom thread pools can generally inherit from the class Threadpoolexcutor, which has several important parameters that determine the policy and processing power of the thread pool.

Threadpoolexecutor (int corepoolsize, int maximumpoolsize, long keepalivetime,timeunit unit,blockingqueue<runnable> WorkQueue, Threadfactory threadfactory, Rejectedexecutionhandler handler)

Corepoolsize-the number of threads that are saved in the pool, including idle threads.

Maximumpoolsize-The maximum number of threads allowed in the pool.

KeepAliveTime-When the number of threads is greater than the core, this is the maximum time to wait for a new task before terminating the extra idle thread.

The time unit of the Unit-keepalivetime parameter.

WorkQueue-the queue used to hold the task before execution. This queue keeps only the Runnable tasks that are submitted by the Execute method.

Threadfactory-The factory that the executor uses when it creates a new thread.

Handler-the handler that is used when execution is blocked because the thread range and queue capacity are exceeded.

These parameters can either be passed in at the time of construction or set by the set method at a later stage.

setmaximumpoolsize (int maximumpoolsize)

Setrejectedexecutionhandler (Rejectedexecutionhandler handler)

Setkeepalivetime (Long time, timeunit unit)

setcorepoolsize (int corepoolsize)

The thread pool expresses the concept of a boundary, which is embodied by Corepoolsize and maximumpoolsize, and if the thread pool accepts tasks that are smaller than corepoolsize, the newly submitted task is processed by the thread pool through the new thread. If it is greater than corepoolsize and less than Maximumpoolsize, the new incoming task is accommodated by the queued queue, and if the queue is not accommodated or if it is a direct-commit queue, the task is submitted to the thread pool, and the thread pool creates a new thread to handle the task. If greater than maximumpoolsize, then the newly added task will be rejected, it should be noted here, the meaning of rejection is not equal to be discarded, but will trigger the thread pool Rejectexecutionhandler, Here we can implement a deny policy for the thread pool by setting a custom handler (such as using a queue to hold a rejected task, and then taking the task from that queue to continue execution).

Choosing the right queue queue is especially important when customizing the thread pool, and we typically have the following three types of queues to choose from

Synchronousqueue directly submits the queue, which does not save the task, but rather puts the task directly to the thread pool.

Linkedblockingqueue unbounded queue, this queue has no limit, you can add unlimited tasks to save, so Maximumpoolsize will not work, the number of threads created will never exceed corepoolsize.

Arrayblockingqueue a bounded queue.

How do I handle a rejected task?

1. Define a policy that is rejected

New tasks submitted in method execute (java.lang.Runnable) are rejected when Executor is closed and Executor uses a limited boundary for the maximum thread and work queue capacity and is already saturated. In both of these cases, the Execute method calls its Rejectedexecutionhandler rejectedexecutionhandler.rejectedexecution (java.lang.Runnable, Java.util.concurrent.ThreadPoolExecutor) method.

Threadpoolexecutor.abortpolicy

The handler for the rejected task, which throws rejectedexecutionexception.

Threadpoolexecutor.discardoldestpolicy

The handler for the rejected task, which discards the oldest unhandled request, retries execute, and discards the task if the execution program is closed.


Threadpoolexecutor.discardpolicy

The handler for the rejected task, which discards the rejected task by default.

2. Custom Rejectedexecutionhandler

Use a custom Rejectedexecutionhandler to define a deny policy for the thread pool, such as using a queue to hold a rejected task for later execution or to discard directly.

More flexible handling

Threadpoolexcutor provides a number of ways to write hooks

AfterExecute (Runnable r,throwable T)

The method invoked based on the completion of execution of the given Runnable.

BeforeExecute (Thread t,runnable R)

The method that is called before executing a given Runnable in a given thread.

These two methods are called back before and after each task is executed by the thread pool, so we can override both methods to customize the required functionality.


How do I handle the concurrency of the thread pool?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.