ThreadPoolExecutor Parameter Parsing, threadpoolexecutor

Source: Internet
Author: User

ThreadPoolExecutor Parameter Parsing, threadpoolexecutor

ThreadPoolExecutor is a very important class used to buildTask executorTo construct a thread pool with different specifications by configuring different parameters.Task executor.

The preface is:

Thread PoolAndTask executorThe thread pool definition is direct. You can view the set of multiple threads. The concept of the task executor is more targeted. It is used to execute tasks and implement multi-task concurrency by managing the thread pool. It is the carrier of the thread pool.

The difference between a thread and a task. A thread is used to execute a task instead of a task.

A queue is used to store tasks, not threads.

Core pool sizes and maxmum pool sizes)

In the beginning, the existence of the two was confusing. The simple idea was to use a pool size to indicate that the size of the thread pool was not enough, if the number of threads is not specified, a new thread is created to execute the new task. When the number of threads is specified, it is waiting for other threads to finish processing. How can we still have two parameters that control the number of threads?

What do these two parameters mean?

Number of core threads: This number has something in common with the number in the preceding simple idea. If the number of current threads cannot reach the number of core threads, the existing Idle threads will not be used (if any ), when a new task is created, a new thread is created.

If the number of threads reaches the core and there are no Idle threads, do you want to create a new thread for a new task? It depends on two points:

This problem can lead to the concept of the maximum number of threads.

Maximum number of threads: The maximum number of threads is used in concert with the task queue. Specifically, it is used in a task queue with a limited length (that is, a bounded task queue.

To answer the above question, the ThreadPoolExecutor thread pool has a task queue, which is used only when the number of threads> Number of core threads are present, if the task queue used by this thread pool is a bounded queue, for example, 10, when the queue is filled with new tasks, that is to say, when there are 10 new tasks in the queue, ThreadPoolExecutor will create a new thread to execute a task in the queue. If the queue is filled again, when there are still no Idle threads, ThreadPoolExecutor creates a new thread again. Once the number of threads is equalMaximum number of threadsNo more threads will be created. If there are 10 tasks in the queue, the new task will be rejected (reject ).

This is for bounded queues. IfTask executorIs it an unbounded queue?

Since the unbounded queue is not filled, it cannot meet the conditions required to create a new thread, so no new thread is created.Maximum number of threadsIn this case, the meaning of its existence is lost.

  • Idle thread survival time(KeepAliveTime)

We have mentioned the number of core threads and the maximum number of threads.Idle threadIdle threads are Idle threads after the task is executed.

If this time is exceeded, Idle threads outside the core thread will be killed. If you want to apply this time to the Core Thread, you need to set it.allowCoreThreadTimeOut(boolean)True

It is necessary to explain how the task executor achieves reuse of threads. When the task executor executes execute (task), a worker is created, which is a Runnable class, it can be seen as the carrier of the task. The worker contains a thread object. When the thread starts, it executes the run method of the worker itself, so that the worker and the thread are integrated. When the worker thread starts, it will execute the worker run method, and the worker run will call the runWorker (worker) of the task executor and pass itself over, this means that the task executor starts a worker, and the key to reuse the thread is in runWorker. After a worker is started, the worker will find a task that can run from the task executor, the task used to create a worker is its first task.

 

The following is the source code of jdk1.7.

// Execute a task taskpublic void execute (Runnable command) {if (command = null) throw new NullPointerException (); int c = ctl. get (); if (workerCountOf (c) <corePoolSize) {if (addWorker (command, true) // assemble the task into a worker and return; c = ctl. get ();} if (isRunning (c) & workQueue. offer (command) {int recheck = ctl. get (); if (! IsRunning (recheck) & remove (command) reject (command); else if (workerCountOf (recheck) = 0) addWorker (null, false);} else if (! AddWorker (command, false) reject (command );}

 

Add a worker

Private boolean addWorker (Runnable firstTask, boolean core) {retry: for (;) {int c = ctl. get (); int rs = runStateOf (c); // Check if queue empty only if necessary. if (rs> = SHUTDOWN &&! (Rs = SHUTDOWN & firstTask = null &&! WorkQueue. isEmpty () return false; for (;) {int wc = workerCountOf (c); if (wc> = CAPACITY | wc> = (core? CorePoolSize: maximumPoolSize) return false; if (compareAndIncrementWorkerCount (c) break retry; c = ctl. get (); // Re-read ctl if (runStateOf (c )! = Rs) continue retry; // else CAS failed due to workerCount change; retry inner loop} boolean workerStarted = false; boolean workerAdded = false; Worker w = null; try {final ReentrantLock mainLock = this. mainLock; w = new Worker (firstTask); final Thread t = w. thread; if (t! = Null) {mainLock. lock (); try {// Recheck while holding lock. // Back out on ThreadFactory failure or if // shut down before lock acquired. int c = ctl. get (); int rs = runStateOf (c); if (rs <SHUTDOWN | (rs = SHUTDOWN & firstTask = null) {if (t. isAlive () // precheck that t is startable throw new IllegalThreadStateException (); workers. add (w); int s = workers. size (); if (s> largestPoolSize) LargestPoolSize = s; workerAdded = true ;}} finally {mainLock. unlock ();} if (workerAdded) {// if the worker is created successfully, start the corresponding thread t. start (); // start workerStarted = true;} finally {if (! WorkerStarted) addWorkerFailed (w);} return workerStarted ;}
Run worker
Final void runWorker (Worker w) {Thread wt = Thread. currentThread (); Runnable task = w. firstTask; w. firstTask = null; w. unlock (); // allow interrupts boolean completedAbruptly = true; try {while (task! = Null | (task = getTask ())! = Null) {// the key here is to use a while to find tasks that have not been executed in the task Executor (mainly obtained from the task queue. W. lock (); // If pool is stopping, ensure thread is interrupted; // if not, ensure thread is not interrupted. this // requires a recheck in second case to deal with // shutdownNow race while clearing interrupt if (runStateAtLeast (ctl. get (), STOP) | (Thread. interrupted () & runStateAtLeast (ctl. get (), STOP )))&&! Wt. isInterrupted () wt. interrupt (); try {beforeExecute (wt, task); Throwable thrown = null; try {task. run ();} catch (RuntimeException x) {thrown = x; throw x;} catch (Error x) {thrown = x; throw x;} catch (Throwable x) {thrown = x; throw new Error (x);} finally {afterExecute (task, thrown) ;}} finally {task = null; w. completedTasks ++; w. unlock () ;}} completedAbruptly = false;} finally {processWorkerExit (w, completedAbruptly );}}

  

 

 


How to parse Python object parameters

Why? Too many? Why ?? Q: What is the sword? Using the function PyArg_ParseTuple () provided by the C language extension interface of mongoj ython to obtain these parameter values, I hope this article will be helpful to you. Python is a scripting language implemented in C language. It has excellent openness and scalability and provides convenient and flexible application interfaces (APIS ). This allows C/C ++ programmers to expand the functions of the Python interpreter at various levels. Before using C/C ++ to Expand functions of Python, you must first understand the C language interface provided by the Python interpretation. Python is an object-oriented scripting language. All objects are expressed as PyObject In the Python interpreter. The PyObject structure contains all member pointers of Python objects. Maintain the type information and reference count of Python objects. During Python extension programming, once Python objects must be processed in C or C ++, A PyObject structure should be maintained. In Python C Language extension interfaces, most functions have one or more parameters of the PyObject pointer type, and most of the returned values are PyObject pointers. To simplify memory management, Python uses the reference counting mechanism to implement automatic garbage collection. Each object in Python has a reference count. It is used to count the number of times the object is referenced in different places. Every time a Python object is referenced, the corresponding reference count increases by 1. Every time a Python object is destroyed, the corresponding reference is reduced by 1. Only when the reference count is zero, to delete Python objects from the memory. The following example illustrates how the Python interpreter manages the Pyhon object using reference count: # include PyObject * wrap_fact (PyObject * self, PyObject * args) {int n, result; if (! PyArg_ParseTuple (args, "I: fact", & n) return NULL; result = fact (n); return Py_BuildValue ("I", result );} static PyMethodDef exampleMethods [] = {"fact", wrap_fact, METH_VARARGS, "Caculate N! "},{ NULL, NULL }}; void initexample () {PyObject * m; m = Py_InitModule (" example ", exampleMethods );} when processing Python objects in C/C ++, correct maintenance of the reference count is a key issue. If it is not handled properly, memory leakage may occur. Python's C language interface provides some macros to maintain the reference count. The most common is to use Py_INCREF () to increase the reference count of Python objects by 1, and use Py_DECREF () to reduce the reference count of Python objects by 1. This function is an interface between the Python interpreter and the C function. It has two parameters: self and args. The self parameter is used only when the C function is implemented as an inline method (built-in method. Generally, the value of this parameter is NULL. The args parameter contains all the parameters that the Python interpreter will pass to the C function, the PyArg_ParseTuple () function provided by the Python C Language extension interface is usually used to obtain these parameter values. Each item in the method list consists of four parts: method name, export function, parameter transfer method, and method description.

How does ScheduledThreadPoolExecutor delete a task?

In this case, you want to delete one of the tasks,
After reading the API, ScheduledThreadPoolExecutor inherits the ThreadPoolExecutor class,
There is:
-------------------------------------
Boolean remove (Runnable task)
Remove this task from the internal queue of the execution Program (if any), so that it does not run if it has not started.
-------------------------------------
The following method is used to return to the task list and execute its contains method, indicating that the task list does not contain my tasks.
-------------------------------------
BlockingQueue <Runnable getQueue ()
Returns the task queue used by the execution program.
-------------------------------------
------ Solution --------------------------------------------------------
The tasks in the task queue are actually packaged for the original task. Therefore, you must delete the parameters returned by scheduleAtFixedRate.
------ Solution --------------------------------------------------------
The API provides a description of this method:
This method can be used as part of the cancellation plan. It may not be able to remove tasks that have been converted to other forms before being placed in the internal queue. For example, tasks input using submit may be converted to maintain the Future State.

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.