Java Concurrency Framework Executor introduction

Source: Internet
Author: User

The Executor framework refers to a number of Executor-related functional classes in a series of concurrency libraries introduced in Java 5, including the thread pool, Executor,executors,executorservice,completionservice, Future,callable and so on.

Their relationship is:

A programming method for concurrent programming is to split the task into columns of small tasks, namely runnable, and then commit to a Executor execution,executor.execute (runnalbe) . The executor uses the internal thread pool to complete the operation at execution time.

First, create a thread pool

The Executors class provides a series of factory methods for creating a first thread pool, and the returned thread pool implements the Executorservice interface.

public static Executorservice newfixedthreadpool (int nthreads)

Creates a thread pool of a fixed number of threads.

public static Executorservice Newcachedthreadpool ()

Creates a cacheable thread pool that calls execute to reuse previously constructed threads if the threads are available. If an existing thread is not available, a new thread is created and added to the pool. Terminates and removes from the cache those threads that have not been used for 60 seconds.

public static Executorservice Newsinglethreadexecutor ()

Create a single-threaded executor.

public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize)

Create a thread pool that supports timed and recurring task executions, which in most cases can be used to replace the timer class.

Java code
Executor Executor = Executors.newfixedthreadpool (ten);  Runnable task = new Runnable () {      @Override public      void Run () {          System.out.println ("task Over");      }  };  Executor.execute (Task);    Executor = Executors.newscheduledthreadpool (ten);  Scheduledexecutorservice Scheduler = (scheduledexecutorservice) executor;  Scheduler.scheduleatfixedrate (Task, ten, Ten, timeunit.seconds);  

  

Second, executorservice and life cycle

Executorservice extends the executor and adds some life-cycle management methods. A executor life cycle has three states, runs , closes , and terminates . Executor is in a running state when it is created. When Executorservice.shutdown () is called, the IsShutDown () method returns true after the shutdown state. At this point, you should not want to add a task in executor, after all the added tasks are completed, executor is in the terminating state, isterminated () returns True.

If executor is turned off, submitting a task to executor throws unchecked exception rejectedexecutionexception.

Java code
Executorservice Executorservice = (executorservice) executor;  while (!executorservice.isshutdown ()) {      try {          Executorservice.execute (Task);      } catch ( Rejectedexecutionexception ignored) {                }  }  Executorservice.shutdown ();  

  

Iii. using Callable,future to return results

Future<v> represents an asynchronous operation, with the Get () method to get the result of the operation, and if the asynchronous operation is not completed, get () blocks the current thread. The futuretask<v> implements Future<v> and runable<v>. Callable represents one with a return worth operation.

Java Code   
callable<integer> func = new callable<integer> () {public Integer call () throws Exception {Syste          M.out.println ("Inside callable");          Thread.Sleep (1000);      return new Integer (8);        }         };  futuretask<integer> futuretask = new Futuretask<integer> (func);  Thread newthread = new Thread (futuretask);    Newthread.start ();      try {System.out.println ("blocking here");      Integer result = Futuretask.get ();  SYSTEM.OUT.PRINTLN (result); } catch (Interruptedexception ignored) {} catch (Executionexception ignored) {} Executoreservice provides the submit () method, passing a CA Llable, or runnable, returns to the future. If the executor background thread pool has not completed the calculation of callable, this call returns the Get () method of the future object, blocking until the calculation is complete. Example: Parallel computation of the and of arrays.    Java Code Collection code package executorservice;  Import java.util.ArrayList;  Import java.util.List;  Import java.util.concurrent.Callable;  Import java.util.concurrent.ExecutionException;  Import Java.util.concurrent.ExecutorService;  Import java.util.concurrent.Executors; IMport Java.util.concurrent.Future;    Import Java.util.concurrent.FutureTask;      public class Concurrentcalculator {private Executorservice exec;      private int cpucorenumber;        Private list<future<long>> tasks = new arraylist<future<long>> ();          Inner class Sumcalculator implements callable<long> {private int[] numbers;          private int start;            private int end;              Public Sumcalculator (final int[] numbers, int start, int end) {this.numbers = numbers;              This.start = start;          This.end = end;              Public Long Call () throws Exception {long sum = 0l;              for (int i = start; i < end; i++) {sum + = numbers[i];          } return sum;          }} public Concurrentcalculator () {cpucorenumber = Runtime.getruntime (). Availableprocessors (); exec = Executors.newfixedthreadpool (cPucorenumber); } public Long sum (final int[] numbers) {//Split task based on number of CPU cores, create futuretask and submit to executor for (int i = 0 ; i < Cpucorenumber;              i++) {int increment = Numbers.length/cpucorenumber + 1;              int start = increment * I;              int end = Increment * i + increment;              if (End > Numbers.length) end = Numbers.length;              Sumcalculator Subcalc = new Sumcalculator (numbers, start, end);              futuretask<long> task = new futuretask<long> (SUBCALC);              Tasks.add (Task);              if (!exec.isshutdown ()) {exec.submit (Task);      }} return GetResult (); }/** * Iterates over each task, obtains parts and, adds returns * * @return */public Long GetResult () {long result          = 0l; for (future<long> task:tasks) {try {//) block Long subsum = t If calculation is not completed Ask.get ();                  result + = Subsum;              } catch (Interruptedexception e) {e.printstacktrace ();              } catch (Executionexception e) {e.printstacktrace ();      }} return result;      } public void Close () {Exec.shutdown ();   }  }

  

Main

Java code
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, ten, one};  Concurrentcalculator calc = new Concurrentcalculator ();  Long sum = calc.sum (numbers);  SYSTEM.OUT.PRINTLN (sum);  Calc.close ();  

  

Iv. Completionservice

In the first example, the GetResult () method iterates over an array of futuretask, and if the task is not completed then the current thread blocks, and if we want the result to be added to result when the arbitrary word task is completed, instead of waiting for each task to complete sequentially, Can make completionservice. The task performed by the producer submit (). The consumer take () completed tasks and processes their results in the order in which they were completed. That is, the take method of calling Completionservice is to return the result of putting the task back in the complete order, Completionservice internally maintains a blocking queue blockingqueue, and if no task is completed, the Take () method is blocked. To modify just the example using Completionservice:

Java code
public class ConcurrentCalculator2 {private Executorservice exec;          Private completionservice<long> Completionservice;        private int cpucorenumber;        Inner class Sumcalculator implements Callable<long> {...}          Public ConcurrentCalculator2 () {cpucorenumber = Runtime.getruntime (). Availableprocessors ();          exec = Executors.newfixedthreadpool (cpucorenumber);          Completionservice = new executorcompletionservice<long> (exec); } public Long sum (final int[] numbers) {//Split task based on number of CPU cores, create futuretask and submit to executor for (int i = 0 ; i < Cpucorenumber;              i++) {int increment = Numbers.length/cpucorenumber + 1;              int start = increment * I;              int end = Increment * i + increment;              if (End > Numbers.length) end = Numbers.length;          Sumcalculator Subcalc = new Sumcalculator (numbers, start, end);     if (!exec.isshutdown ()) {completionservice.submit (SUBCALC);      }} return GetResult (); }/** * Iterates over each task, obtains parts and, adds returns * * @return */public Long GetResult () {long result          = 0l; for (int i = 0; i < Cpucorenumber; i++) {try {Long subsum = Completionservi                  Ce.take (). get ();                         result + = Subsum;              } catch (Interruptedexception e) {e.printstacktrace ();              } catch (Executionexception e) {e.printstacktrace ();      }} return result;      } public void Close () {Exec.shutdown ();   }  }

  

V. Use of the scene

1. Can be used instead of timer to do timed tasks

2. The original slow code in the transformation project, cut into multiple blocks, run in multiple threads, and the final result is then integrated together

3. Code executes asynchronously, returning the main part first

Wait a minute

Java Concurrency Framework Executor introduction

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.