Android thread pool (2) -- Example of ThreadPoolExecutor and its rejection policy RejectedExecutionHandler, threadpoolexecutor

Source: Internet
Author: User

Android thread pool (2) -- Example of ThreadPoolExecutor and its rejection policy RejectedExecutionHandler, threadpoolexecutor
MainActivity is as follows:

Package cc. vv; import java. util. concurrent. linkedBlockingQueue; import java. util. concurrent. threadPoolExecutor; import java. util. concurrent. timeUnit; import android. OS. bundle; import android. app. activity;/*** Demo Description: * ThreadPoolExecutor and its rejection policy (RejectedExecutionHandler) Example ** Working principle: * The thread pool mainly involves corePoolSize, workQueue, maximumPoolSize, RejectedExecutionHandler * Call principle: * 1 when the number of threads in the thread pool is less than corePoolSiz E is used to create a thread and process the request. * 2 when the number of threads in the thread pool is equal to corePoolSize, the request is put into workQueue, the Idle threads in the thread pool fetch tasks from the workQueue and process the tasks. * 3 when the workQueue is full and cannot store new tasks, the new thread enters the pool and processes the requests; * if the number of threads in the thread pool is greater than maximumPoolSize, use RejectedExecutionHandler to apply certain policies for Denial of Service. ** the mechanism also contains keepAliveTime, which is described as follows: * when the number of threads is greater than the core, * this is the maximum time that excess idle threads will wait for new tasks before terminating. * What does it mean? * For example, there are five threads in the thread pool, three of which are core threads and the other two are non-core threads. * When the non-core thread of keepAliveTime is still idle (that is, No task is executed or no task can be executed), the non-core thread will be terminated. * This is the maximum duration for non-core and Idle threads in the thread pool. After this time is exceeded, the thread is terminated. * ** four denial policies of RejectedExecutionHandler ** hreadPoolExecutor. abortPolicy: * If the number in the thread pool is equal to the maximum number of threads, java is thrown. util. concurrent. rejectedExecutionException. * tasks involving this exception will not be executed. ** ThreadPoolExecutor. callerRunsPolicy (): * When the number in the thread pool is equal to the maximum number of threads, the current task is retried. It will automatically call the execute () method again ** ThreadPoolExecutor. discardOldestPolicy (): * when the number of threads in the thread pool is equal to the maximum number of threads, discard the tasks in the Job Queue header in the thread pool (that is, the Oldest task with the longest wait time ), and execute the new input task ** ThreadPoolExecutor. discardPolicy (): * When the number in the thread pool is equal to the maximum number of threads, discard new tasks that cannot be executed. ** reference: * http://blog.csdn.net/cutesource/article/details/6061229 * http://blog.csdn.net/longeremmy/article/details/8231184 * http://blog.163.com/among_1985/blog/static/275005232012618849266/ * http://blog.csdn.net/longeremmy/article/details/8231184 * http://ifeve.com/java-threadpool/ * http://www.blogjava.net/xylz/archive/2010/07/08/325587.html * http://blog.csdn.net/ns_code/article/details/17465497 * Thank you very much */public class MainActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); testRejectedExecutionHandler () ;}// test the four policies here and replace the last parameter of the ThreadPoolExecutor () method. private void testRejectedExecutionHandler () {int produceTaskMaxNumber = 10; // construct a thread pool ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor (2, 4, 3, TimeUnit. SECONDS, new LinkedBlockingQueue <Runnable> (3), new ThreadPoolExecutor. discardPolicy (); for (int I = 1; I <= produceTaskMaxNumber; I ++) {try {String task = "task" + I; System. out. println ("put" + task + "into the thread pool" into threadpoolexecutor.exe cute (new RunnableImpl (task);} catch (Exception e) {e. printStackTrace (); System. out. println ("AbortPolicy throws an exception ---->" + e. toString () ;}} private class RunnableImpl implements Runnable {private String taskName; private int consumerTaskSleepTime = 2000; RunnableImpl (String taskName) {this. taskName = taskName;} public void run () {System. out. println ("START" + taskName); try {// simulate time-consuming task Thread. sleep (consumerTaskSleepTime);} catch (Exception e) {e. printStackTrace ();} System. out. println ("finished" + taskName );}}}

Main. xml is as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></RelativeLayout>



Question about creating a self-contained thread pool in JAVA

RejectedExecutionHandler handler: The processing policy of the thread pool to reject tasks;
For details, when the Executor has been disabled and the Executor uses the finite boundary for the maximum thread and working queue capacity and is saturated, execute (java. lang. runnable. In both cases, the execute method calls the RejectedExecutionHandler's RejectedExecutionHandler. rejectedExecution (java. lang. Runnable, java. util. concurrent. ThreadPoolExecutor) method.

New ThreadPoolExecutor. DiscardOldestPolicy () is used as the last parameter.

Generally, handler has four predefined processing policies:

A. in the default ThreadPoolExecutor. AbortPolicy, A running RejectedExecutionException will be thrown if the handler is rejected.

B. In ThreadPoolExecutor. CallerRunsPolicy, the thread calls the execute itself that runs the task. This policy provides a simple feedback control mechanism to speed down the submission of new tasks.

C. In ThreadPoolExecutor. DiscardPolicy, tasks that cannot be executed will be deleted.

D. In ThreadPoolExecutor. DiscardOldestPolicy, if the execution program is not closed, the task in the Job Queue header will be deleted, and then the execution program will be retried (if the execution fails again, the process will be repeated ).

Defining and using other types of RejectedExecutionHandler classes is also possible, but you need to be very careful when doing so, especially when the policy is only used for a specific capacity or queuing policy.

Hello ~ I have taught you how to set the maximum number of threads in a thread pool properly before creating a thread pool?

RejectedExecutionHandler handler: The processing policy of the thread pool to reject tasks;
For details, when the Executor has been disabled and the Executor uses the finite boundary for the maximum thread and working queue capacity and is saturated, execute (java. lang. runnable. In both cases, the execute method calls the RejectedExecutionHandler's RejectedExecutionHandler. rejectedExecution (java. lang. Runnable, java. util. concurrent. ThreadPoolExecutor) method.

New ThreadPoolExecutor. DiscardOldestPolicy () is used as the last parameter.

Generally, handler has four predefined processing policies:

A. in the default ThreadPoolExecutor. AbortPolicy, A running RejectedExecutionException will be thrown if the handler is rejected.

B. In ThreadPoolExecutor. CallerRunsPolicy, the thread calls the execute itself that runs the task. This policy provides a simple feedback control mechanism to speed down the submission of new tasks.

C. In ThreadPoolExecutor. DiscardPolicy, tasks that cannot be executed will be deleted.

D. In ThreadPoolExecutor. DiscardOldestPolicy, if the execution program is not closed, the task in the Job Queue header will be deleted, and then the execution program will be retried (if the execution fails again, the process will be repeated ).

Defining and using other types of RejectedExecutionHandler classes is also possible, but you need to be very careful when doing so, especially when the policy is only used for a specific capacity or queuing policy.

 

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.