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

Source: Internet
Author: User

Overview

This chapter describes the callable and future in thread pooling.
Introduction to Callable and future
Sample and source analysis (based on jdk1.7.0_40)

Reprint Please specify source: http://www.cnblogs.com/skywang12345/p/3544116.html

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:

Interface callable<v> {    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:

PublicInterface future<v>{//An attempt was made to cancel execution of this task.Boolean Cancel (Booleanmayinterruptifrunning)//boolean iscancelled ()  boolean IsDone () //< Span style= "color: #008000;" If necessary, wait for the calculation to complete and then get its results. V get () throws Interruptedexception, Executionexception; //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:

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.

1Importjava.util.concurrent.Callable;2ImportJava.util.concurrent.Future;3ImportJava.util.concurrent.Executors;4ImportJava.util.concurrent.ExecutorService;5ImportJava.util.concurrent.ExecutionException;67Class MycallableImplementsCallable {89@Override10Public Integer Call ()ThrowsException {11int sum = 0;12//Perform tasks13for (int i=0; i<100; i++)Sum + =I15//return sum;16ReturnInteger.valueof (sum);17}18}1920PublicClassCallableTest1 {21st22PublicStaticvoidMain (string[] args)23ThrowsExecutionexception, interruptedexception{24//Create a pool of threadsExecutorservice pool =Executors.newsinglethreadexecutor ();26//27 Callable C1 = new mycallable ();  // perform tasks and get future objects  Pool.submit (C1); // output 31  System.out.println (F1.get ()); 32 // close thread pool 33  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) {    new// Create a Runnablefuture object runnablefuture<t> Ftask =// Execute "task 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) {    new futuretask<t >(callable);}  

2. Futuretask constructor

The Futuretask constructor is as follows:

Public Futuretask (callable<v> callable) {    null)        new//this.callable =// // 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:

PublicvoidRun () {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;BooleanRanTry{//Executes the call () method of the callable and saves the results to result. result =C.call (); Ran =True; }catch (Throwable ex) {result = nullfalse//finally {runner = null< Span style= "color: #000000;" >; // set "state status Tag" int s =  State; 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 Multithreading Series--"Juc thread pool" 06 of the 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.