Java-"Juc thread pool" callable and future

Source: Internet
Author: User

Java Multithreading Series--"Juc thread pool" 06 of the callable and future

Introduction to Callable and future

Callable and future are more interesting pairs of combinations. When we need to get the execution results of threads, we need to use them. Callable is used to produce results, and the future is used to obtain results.

1. Callable

Callable is an interface that contains only a call () method. Callable is a task that returns results and can throw exceptions.

For the sake of understanding, we can compare callable to a runnable interface, and callable's call () method is similar to the runnable run () method.

The source code of callable is as follows:

Public interface Callable<v> {    V call () throws Exception;}

description : from which we can see that callable supports generics.

2. Future

The future is an interface. It is used to represent the result of an asynchronous calculation. Provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the results of the calculation.

Future source code is as follows:

Public interface Future<v> {    //attempted to cancel execution of this task.    Boolean     Cancel (boolean mayinterruptifrunning)    //Returns True if it is canceled before the task is completed properly.    boolean     iscancelled ()    //Returns True if the task is completed.    boolean     isDone ()    //wait for the calculation to complete if necessary, and then get its results.    V           Get () throws Interruptedexception, Executionexception;    If necessary, wait for the result to be obtained (if the result is available) after the time given for the calculation to complete.    V             Get (long timeout, timeunit unit)          throws Interruptedexception, Executionexception, timeoutexception ;}

Description : The future is used to represent the result of an asynchronous calculation. Its implementation class is Futuretask, before explaining Futuretask, we first look at callable, future, futuretask the diagram between them, as follows:

Description :
Runnablefuture is an interface that inherits both the runnable and the future interfaces. The source code of Runnablefuture is as follows:

Public interface runnablefuture<v> extends Runnable, future<v> {    void run ();

(Futuretask) implements the Runnablefuture interface. So, we also say that it implements the future interface.

Sample and source analysis (based on jdk1.7.0_40)

Let's start with an example of the basic usage of callable and future, and then analyze the implementation of the example.

 1 Import java.util.concurrent.Callable; 2 Import java.util.concurrent.Future; 3 Import java.util.concurrent.Executors; 4 Import Java.util.concurrent.ExecutorService; 5 Import java.util.concurrent.ExecutionException; 6 7 class Mycallable implements callable {8 9 @Override public Integer call () throws Exception {one I NT sum = 0;12//Perform task for (int i=0; i<100; i++) sum + = i;15//return sum; return integer.valueof (sum), +}19 public class CallableTest1 {$ public static void main (St Ring[] args) throws Executionexception, interruptedexception{24//Create a thread pool Executorservice poo L = Executors.newsinglethreadexecutor (); 26//Create a task with a return value callable C1 = new mycallable (); 28//Perform the task and Get Future Object f1 = Pool.submit (c1); 30//Output result is System.out.println (F1.get ()); 32//Close thread pool Pool.shutdown (); 34}35}

Operation result :

4950

Result Description :
In main thread main, create a new thread pool through Newsinglethreadexecutor (). The callable object C1 is then created, and then the C1 is submitted to the thread pool through Pool.submit (c1) for processing, and the returned results are saved to the future object F1. We then get the saved results from the callable through F1.get () and finally close the thread pool through Pool.shutdown ().

1. Submit ()

Submit () implemented in Java/util/concurrent/abstractexecutorservice.java, its source code is as follows:

Public <T> future<t> Submit (callable<t> Task) {    if (task = = null) throw new NullPointerException ();    //Create a Runnablefuture object    runnablefuture<t> ftask = newtaskfor (Task);    Execute "task Ftask"    execute (ftask);    Return "Ftask" return    Ftask;}

Description: Submit () created the Runnablefuture object Ftask through Newtaskfor (Task). Its source code is as follows:

Protected <T> runnablefuture<t> newtaskfor (callable<t> callable) {    return new futuretask<t > (callable);}

2. Futuretask constructor

The Futuretask constructor is as follows:

Public Futuretask (callable<v> callable) {    if (callable = = null)        throw new NullPointerException ();    Callable is a callable object    this.callable = callable;    State record Futuretask status    this.state = NEW;       Ensure visibility of callable}

3. Futuretask's Run () method

We continue to return to the source of the submit ().
After Newtaskfor () creates a new Ftask object, the task is executed through execute (ftask). At this point the ftask is executed as a Runnable object and will eventually be called to its run () method, and the Ftask run () method is implemented in Java/util/concurrent/futuretask.java, the source code is as follows:

public void Run () {    if ' state! = NEW | |        ! Unsafe.compareandswapobject (This, runneroffset,                                     null, Thread.CurrentThread ()))        return;    try {        //assigns the callable object to C.        callable<v> C = callable;        if (c! = null && state = = NEW) {            V result;            Boolean ran;            try {                //executes the call () method of callable and saves the result to results.                result = C.call ();                ran = true;            } catch (Throwable ex) {                result = null;                ran = false;                SetException (ex);            }            If the run succeeds, the result is saved if            (RAN)                set (result);}    } finally {        runner = null;        Set "state status token"        int s = states;        if (s >= interrupting)            Handlepossiblecancellationinterrupt (s);    }}

Description : The call () method of the callable object is executed in run (), and the result is eventually saved to result, and the result is saved through set (result).
The Get () method of Futuretask is then called, and the value saved by set (result) is returned.

Java-"Juc thread pool" callable and future

Related Article

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.