Java Concurrency Executor framework

Source: Internet
Author: User

1 Executor Framework Introduction

Starting with JDK5, the unit of work and the implementation mechanism are isolated and the unit of work includes runnable and callable, and the implementation mechanism is provided by executor.

Call Relationships: Java threads Map a one-to-one system thread to the local operating system, and when multithreaded programs decompose several tasks, use the user-level scheduler (Executor framework) to map tasks to a fixed number of threads, the underlying, the operating system, and the kernel to map these threads to the hardware processor.

2.EXecutor Structure Members

Executor is an interface that separates the submission of a task from the execution of a task.

Threadpoolexecutor is the core implementation class of the thread pool that performs the submitted task

Scheduledthreadpoolexecutor is an implementation class that runs after a given delay or executes a command on a regular basis

The future interface and the Futuretask class that implements the future interface, representing the results of asynchronous computations

Runable interface and callable interface implementation class, can be Threadpoolexecutor or scheduledthreadpoolexecutor execution

2.1 Use Flow

(1) Create a Task object

Create a Task object that implements the Runnable interface or callable interface. Runnable does not return results, callable can return results

You can use the factory class executors to encapsulate the runnable into a callable

public static callable<object> callable (Runnable Task)

Executors.callable (Runnable Task) or executors.callable (Runnable task,object result)

(2) Object submission execution

Give the Runnable object directly to Executorservice execution (executorservice.execute (Runnable command); Executorservice.submit (Runnable Task); Executorservice.submit (callable<t> Task)). The Execute () method submits a task that does not require a return value and cannot determine whether the task was successfully executed by the thread pool. Submit () is used to commit a task that requires a return value.

(3) Return value

If Executorservice.submit (...) is executed, an object Futuretask object that implements the future interface is returned, and the main thread can execute the Futuretask.get () method to wait for the task to complete. You can also perform Futuretask.cancel (Boolean mayinterruptifrunning) to cancel the execution of a task.

2.2 Framework Members

Threadpoolexecutor, Scheduledthreadpoolexecutor, future interface, runnable interface, callable interface, executors.

2.2.1 Thread Pool Introduction

Public threadpoolexecutor (int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,BlockingQueue< runnable> workqueue,threadfactory Threadfactory,rejectedexecutionhandler handler)

Corepoolsize: The basic size of the thread pool, when a new task arrives, creates a thread to perform the task, even if other idle basic threads are able to perform a new task, the thread is created when the number of tasks that need to be performed is greater than the thread pool base size. If you call the Prestartallcorethread () method of the thread pool, the thread pool creates and starts all basic threads in advance.

Maximumpoolsize: The maximum number of thread pools, the maximum number of threads allowed to be created by the thread pool, the creation of a new thread if the queue is full and the number of threads created is less than the maximum number of threads, which is not valid for unbounded queues.

KeepAliveTime: Thread activity hold time, time when worker threads are idle, and if the task has a short execution time for each task, it can be adjusted to increase thread utilization

Timeunit: Thread activity hold time unit, selectable unit, Days,hours,minutes,milliseconds,microseconds,nanoseconds

Blockingqueue<runnable>: Task queue, blocking queue waiting to perform task, Arrayblockingqueue: bounded blocking queue based on array structure, sorted by FIFO, Linkedblockingqueue: A list-based blocking queue, sorted by FIFO, with throughput higher than the former, Executors.newfixedthreadpool () uses the queue. Sysnchronousqueue: A blocking queue that does not store elements, each insert operation must wait for another thread to invoke the remove operation, otherwise the insert operation is stuck and throughput is higher than the former. Executors.newcachedthreadpool () uses this queue, Priorityblockingqueue: A wireless blocking queue with priority.

Threadfactory: Used to set the factory for creating threads, you can set a meaningful name for each thread through the thread factory, which can be set by default.

Rejectedexecutionhandler: Saturation policy, when the queue and thread pool are full, a policy must be taken to handle the newly submitted task. Default AbortPolicy: Throws an exception directly. Callerrunspolicy: Runs the task only with the caller's thread, Discardoldestpolicy: Discards the most recent task in the queue and executes the current task; Discardpolicy: Do not process, discard.

2.2.1.1 thread pool processing process

1) The thread pool determines whether threads in the core line constructor are performing tasks. No, create a new thread to perform the task, if all in the execution task goes to the next step;

2) The thread pool determines whether the work queue is full, and the newly submitted task is stored in the work queue, full of the next step;

3) The thread pool determines whether threads in the thread pool are in a working state. No, create a new worker thread to perform the task, full over to the saturation policy processing.

Threadpoolexecutor Execute Execute () method flow:

1) If the currently running thread is less than corepoolsize, create a new thread to perform the task (the step needs to obtain a global lock)

2) If the running thread is equal to or more than Corepoolsize, the task is added to the blockingqueue;

3) If the queue is full and cannot join the task to the queue, create a new thread to process the task (this step acquires a global lock)

4) If you create a new thread that will cause the currently running thread to exceed maximumpoolsize, the task will be rejected and the Rejectedexecutionhandle.rejectedexecution () method is called.

2.2.2 Threadpoolexecutor

Fixedthreadpool, creates a scenario that uses a fixed number of threads, in order to meet the needs of resource management, and needs to limit the current number of threads, for servers with heavier load

public static Executorservice newfixedthreadpool (int nthreads) {

return new Threadpoolexecutor (Nthreads,nthreads,0l,timeunit.milliseconds,new linkedblockingqueue<runnable> ( ));

}

Singlethreadpool, creates a scenario that uses a single thread, is suitable for guaranteeing sequential execution of individual tasks, and does not have multiple threads active at any point in time, and can be used to handle shared resource issues

public static Executorservice Newsinglethreadexecutor () {

return new Threadpoolexecutor (1,1,0l,timeunit.milliseconds,new linkedblockingqueue<runnable> ());

}

Cachedthreadpool, Creation creates new threads as needed, initializes a certain number of threads, creates new threads when new tasks arrive without idle threads, and has idle reuse of previous threads

public static Executorservice Newcachedthreadpool () {

return new Threadpoolexecutor (0,integer.max_value,60l,timeunit.seconds,new sysnchronousqueue<runnable> ());

the idle thread will terminate for more than 60 seconds

2.2.3 Scheduledthreadpoolexecutor

Scheduledthreadpoolexecutor inherits Threadpoolexecutor, which is used to perform tasks after a given delay or perform tasks on a regular basis, and is more flexible than a timer The timer corresponds to a single background thread and Scheduledthreadpoolexecutor can specify more than one corresponding number of background threads in the constructor.

There are at least 2 methods in Scheduledexecutorservice that can be used to perform tasks periodically.

Scheduleatfixedrate (Runnable command,long initialdelay,long period,timeunit unit)

We can use this method to delay the execution of a task and set the execution period of the task. The time period is counted from the thread that first executes in the thread pool, so assuming that period is 1s and the thread executes 5s, the next thread will be executed shortly after the first thread has run out.

For example, the following code

for (int i = 0; i < 3; i++) {    thread.sleep (+);    Workerthread worker = new Workerthread ("Do heavy Processing");    Schedule task to execute at fixed rate    scheduledthreadpool.scheduleatfixedrate (worker, 0,            Timeunit.seconds);
Output
Current time = Tue Oct 16:10:00 IST 2013pool-1-thread-1 Start. Time = Tue Oct 16:10:01 IST 2013pool-1-thread-2 Start. Time = Tue Oct 16:10:02 IST 2013pool-1-thread-3 Start. Time = Tue Oct 16:10:03 IST 2013pool-1-thread-1 End. Time = Tue Oct 16:10:06 IST 2013pool-1-thread-2 End. Time = Tue Oct 16:10:07 IST 2013pool-1-thread-3 End. Time = Tue Oct 16:10:08 IST 2013pool-1-thread-1 Start. Time = Tue Oct 16:10:11 IST 2013pool-1-thread-4 Start. Time = Tue Oct 16:10:12 IST 2013
Schedulewithfixeddelay (Runnable command,long initialdelay,long delay,timeunit unit)This method can be used to delay periodic execution of a task, delaytime is the delay between the time the thread stops execution and the next execution, assuming the following code
for (int i = 0; i < 3; i++) {    thread.sleep (+);    Workerthread worker = new Workerthread ("Do heavy Processing");    Scheduledthreadpool.schedulewithfixeddelay (worker, 0, 1,            timeunit.seconds);}
Output results
Current time = Tue Oct 16:14:13 IST 2013pool-1-thread-1 Start. Time = Tue Oct 16:14:14 IST 2013pool-1-thread-2 Start. Time = Tue Oct 16:14:15 IST 2013pool-1-thread-3 Start. Time = Tue Oct 16:14:16 IST 2013pool-1-thread-1 End. Time = Tue Oct 16:14:19 IST 2013pool-1-thread-2 End. Time = Tue Oct 16:14:20 IST 2013pool-1-thread-1 Start. Time = Tue Oct 16:14:20 IST 2013pool-1-thread-3 End. Time = Tue Oct 16:14:21 IST 2013pool-1-thread-4 Start. Time = Tue Oct 16:14:21 IST 2013

Java Concurrency Executor framework

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.