Java concurrent programming series 15th: Executor framework

Source: Internet
Author: User

Java concurrent programming series 15th: Executor framework

It is common for Java to use threads to complete asynchronous tasks, and the creation and destruction of threads requires a certain amount of overhead. If each task needs to create a thread, it will consume a lot of computing resources, after JDK 5, the work units and execution mechanisms are separated. The work units include Runnable and Callable, while the execution mechanism is provided by the Executor framework. The Executor framework facilitates thread startup, execution, and shutdown. The underlying layer uses the thread pool for implementation. The advantage of using the Executor framework to manage threads is to simplify management, improve efficiency, and avoid this escape problem-that is, incomplete objects are called by threads.

The Executor framework uses two-level scheduling models for thread scheduling. At the upper layer, Java multi-threaded programs usually break down applications into multiple tasks, and then use the user scheduling framework Executor to map these tasks to a fixed number of threads. At the bottom layer, the operating system kernel maps these threads to the hardware processor.

Executor framework includes thread pool, Executor, Executors, ExecutorService, CompletionService, Future, C
Allable.

The main thread first creates a task object through the Runnable or Callable interfaces. Tool class Executors can encapsulate a Runnable object as a Callable object (by calling Executors. callable (Runnable cute (Runnable command) to complete the task execution; or give the Runnable object or Callable object to ExecutorService for execution. ExecutorService calls ExecutorService. submit (Runnable task) or ExecutorService. submit (Callable task) completes task submission. When the submit method of ExecutorService is used, an object implementing the Future interface will be returned (the FutureTask object is currently returned ). Because FutureTask implements Runnable, you can also directly create FutureTask and hand it over to ExecutorService for execution.

The ExecutorService interface inherits from the Executor interface, which provides richer methods to implement multithreading. For example, you can call the shutdown () method of ExecutorService to smoothly disable ExecutorService. After this method is called, it will cause ExecutorService to stop accepting any new tasks and wait until the execution of the submitted tasks is completed (the submitted tasks are classified into two types: one is already executed, another type is not started yet). When all submitted tasks are completed, ExecutorService is disabled.

You can use the Executors tool class to create different thread pools ThreadPoolExecutor: SingleThreadExecutor, FixedThreadPool, and CachedThreadPool.

FixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads)public static ExecutorService newFixedThreadPool(int nThreads,ThreadFactory factory)

FixedThreadPool is applicable to scenarios where the current number of threads needs to be limited to meet resource management requirements. It is suitable for servers with heavy loads.

SingleThreadExecutor

public static ExecutorService newSingleThreadExecutor()public static ExecutorService newSingleThreadExecutor(ThreadFactory factory)

SingleThreadExecutor is applicable to scenarios where tasks need to be executed sequentially without multiple threads active at any time point.

CachedThreadPool

public static ExecutorService newCachedThreadPool()public static ExecutorService newCachedThreadPool(ThreadFactory factory)

CachedThreadPool is an unbounded thread pool, suitable for small programs that execute many short-term asynchronous tasks, or servers with lighter load ratio.

ScheduledThreadPoolExecutor

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize,ThreadFactory factory)

Create a thread pool that supports scheduled and periodic task execution. In most cases, it can be used to replace the Timer class. ScheduledThreadPoolExecutor is applicable to scenarios where periodic tasks need to be executed in multiple backend threads and the number of backend threads must be limited to meet resource management requirements.

The core class of the Executor framework isThreadPoolExecutorIt is the implementation class of the thread pool and consists of four components.

CorePool: size of the Core Thread Pool maximumPool: size of the maximum thread pool BlockingQueue: used to temporarily Save the Job Queue RejectedExecutionHandler: Saturation policy. When ThreadPoolExecutor is closed or ThreadPoolExecutor is saturated (the maximum thread pool size is reached and the working queue is full), the Handler to be called by the execute Method

 

Run the Runnable task using the Executor framework

package com.rhwayfun.concurrency;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * Created by rhwayfun on 16-4-4. */public class ExecutorRunnableTest {    static class Runner implements Runnable{        public void run() {            System.out.println(Thread.currentThread().getName() + " is called");        }    }    public static void main(String[] args){        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();        for (int i = 0; i < 5; i++){            cachedThreadPool.execute(new Runner());        }        cachedThreadPool.shutdown();    }}

The result is as follows:

Through the analysis of the CachedThreadPool, we can know that when executing a task, we will first select an idle thread from the thread pool to execute the task, if there is no idle thread, a new thread will be created to execute the task. The reason why the same thread executes the task twice is that the idle thread that executes the task for the first time does not terminate the task immediately after the task is executed.

Use Executor framework to execute Callable tasks

The Runnable task does not return values, but the Callable task does. Besides, the call () method of Callable can only be executed through the submit (Callable task) method of ExecutorService, and a Future (currently FutureTask) is returned, which indicates the Future of the task waiting to be completed. If you want to obtain the result returned by Callable execution, you can use the get method of the uretask bucket.

The following code demonstrates executing a Callable task using the Executor framework:

Package com. rhwayfun. concurrency; import java. util. arrayList; import java. util. list; import java. util. concurrent. *;/*** Created by rhwayfun on 16-4-4. */public class ExecutorCallableTest {/*** Callable task */static class Runner implements Callable
  
   
{Private String runId; public Runner (String runId) {this. runId = runId;} public String call () throws Exception {System. out. println (Thread. currentThread (). getName () + "call method is invoked! "); Return Thread. currentThread (). getName () + "call method and id is" + runId;} public static void main (String [] args) {// thread pool ExecutorService cachedThreadPool = Executors. newCachedThreadPool (); // List of returned results for receiving Callable tasks
   
    
> FutureTaskList = new ArrayList
    
     
> (); For (int I = 0; I <5; I ++) {Future
     
      
Future = cachedThreadPool. submit (new Runner (String. valueOf (I); futureTaskList. add (future);} // traverses the returned results of thread execution for (Future f: futureTaskList) {try {// wait while (! F. isDone () {} System. out. println (f. get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace ();} finally {// close the thread pool and no longer receive new job cachedThreadPool. shutdown ();}}}}
     
    
   
  

The program running result is as follows:

The submit method also selects the idle thread to execute the task first. If there is no, a new thread will be created to execute the task. If the Future return is not completed, the get () method will block the wait until the Future completion returns.
 

FixedThreadPool details

The source code for creating FixedThreadPool is as follows:

public static ExecutorService newFixedThreadPool(int nThreads) {        return new ThreadPoolExecutor(nThreads, nThreads,                                      0L, TimeUnit.MILLISECONDS,                                      new LinkedBlockingQueue
  
   ());    }
  

Both corePoolSize and maximumPoolSize are set to nThreads values. When the number of threads in the thread pool is greater than corePoolSize, keepAliveTime is the maximum time for redundant Idle threads to wait for a new task. After this time is exceeded, excessive threads will be terminated. The specific execution process in FixedThreadPool is as follows:

If the number of currently running threads is less than corePoolSize, a new thread execution task is created in the thread pool. If the number of currently running threads is equal to corePoolSize, after a task is added to the LinkedBlockingQueue wait for the execution thread to finish the task 1, the task is retrieved from the LinkedBlockingQueue repeatedly in the loop for execution.

Because the unbounded queue used by LinkedBlockingQueue, the number of threads in the thread pool does not exceed corePoolSize. Therefore, tasks that are constantly added to the thread pool will be executed, because all tasks that will not be executed immediately are added to the queue blockingqueue.

CachedThreadPool details

CachedThreadPool is a thread pool that creates threads as needed. The source code for creating a CachedThreadPool is as follows:

public static ExecutorService newCachedThreadPool() {        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                      60L, TimeUnit.SECONDS,                                      new SynchronousQueue
  
   ());    }
  

As can be seen from the source code, the corePoolSize of CachedThreadPool is 0, maximumPoolSize is Integer. MAX_VALUE, and keepAliveTime is 60L, meaning that the redundant Idle threads wait for the execution time of new tasks to 60 seconds.

CachedThreadPool uses non-capacity SynchronousQueue as the working queue of the thread pool (SynchronousQueue is a non-capacity blocking queue, and each insert operation must wait for the corresponding removal operation of another thread ), however, the maximumPool of the CachedThreadPool is unbounded. This means that if the thread's submission speed is higher than the thread's processing speed, CachedThreadPool will constantly create threads. The extreme reason is that the creation thread consumes too many CPU and memory resources.

The execution process of CachedThreadPool is as follows:

First, execute the offer method of SynchronousQueue. If maximumPool has Idle threads, SynchronousQueue is being executed. poll (keepAliveTime, TimeUnit. NANOSECONDS), then the master thread executes the offer operation and the poll operation of the idle thread is paired successfully, and the master thread submits the task to the idle thread for execution, otherwise, if maximumPool is empty or maximumPool has no Idle threads, CachedThreadPool will create a new thread to execute the task. After the newly created thread in step 2 finishes the task, wait for 60 seconds in the SynchronousQueue queue. If the main thread submits a new task within 60 seconds, the new task submitted by the main thread will continue to be executed. Otherwise, the idle thread will be terminated. ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, which is mainly used to execute tasks after a given delay or regularly run tasks. The Timer class also has similar functions. Timer corresponds to a single background thread, while ScheduledThreadPoolExecutor can specify multiple corresponding background threads in the constructor.

To support periodic task execution, ScheduledThreadPoolExecutor uses DelayQueue as the task queue. ScheduledThreadPoolExecutor places the task to be scheduled (ScheduledFutureTask) in DelayQueue. The thread in the thread pool obtains and executes the scheduled task from DelayQueue.

ScheduledFutureTask contains three variables:

The long variable time is the execution time of the task. The long variable sequenceNumber is the period of the long member added to ScheduledThreadPoolExecutor, indicating the execution interval of the task.

The following describes how to execute ScheduledThreadPoolExecutor:

The thread obtains the expired ScheduledFutureTask from DelayQueue. An expiration task refers to the time variable when the task thread with a time greater than or equal to the current time executes the expired task thread and modifies the task to the next execution time (the current time plus the interval) the thread puts the modified task back into DelayQueue and will be re-executed after expiration.

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.