Concurrent Programming-callable and Future

Source: Internet
Author: User

Java concurrent programming practice directory

Concurrent Programming-concurrenthashmap

Concurrent Programming-blocking queue and producer-consumer Mode

Concurrent Programming -- locking countdownlatch and barrier

Concurrent Programming-callable and Future

 

Overview

Part 1 callable

Part 1 Future

Part 1 examples and source code analysis

3.1 submit ()

3.2 uretask Constructor

3.3 run () method of futuretask

Reference

 

Callable and future are interesting combinations. When we need to obtain the thread execution results, we need to use them. Callable is used to generate results, and future is used to obtain results.

Part 1 callable

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

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

The source code of callable is as follows:

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

CallableThe interface is similarRunnableBoth are designed for classes whose instances may be executed by another thread. HoweverRunnableNo results are returned, and a checked exception cannot be thrown.

ExecutorsThe class contains some elements that are converted from other common formsCallableClass.

 

Part 1 Future

Future is an interface. It is used to represent the result of asynchronous calculation. It provides a method to check whether the calculation is complete, waiting for the calculation to be completed and obtaining the calculation result.

The source code of future is as follows:

Boolean cancel (Boolean mayinterruptifrunning) tries to cancel the execution of this task. If necessary, wait until the calculation is complete and obtain the result. V get (long timeout, timeunit unit), if necessary, waits until the result is obtained (if the result is available) after the given time for the calculation to complete ). Boolean iscancelled () returns true if it is canceled before the task is completed normally. Boolean isdone () returns true if the task has been completed.

 

Before explaining futuretask, let's take a look at the relationships between callable, future, and futuretask, as shown below:

 

Future indicates the life cycle of a task, and provides methods to determine whether the task has been completed or canceled, as well as to obtain the task result and cancel the task. The implicit meaning in the future specification is that the life cycle of a task can only advance and cannot be retired, just like the life cycle of executorservice. After a task is completed, it will always stay in the "finished" state.

The action of the get method depends on the status of the task (not started, running, and completed ). If the task has been completed, get will immediately return or throw an exception. if the task is not completed, get will be blocked until the task is completed. If the task throws an exception, get encapsulates the exception as executionexception and throws it again. If the task is canceled, get will throw cancellationexception. If get throws executionexception, you can use getcause to obtain the encapsulated initial exception.

Exception thrown: cancellationexception-executionexception canceled if computing is canceled-interruptedexception thrown if computing is aborted-timeoutexception if the current thread is interrupted while waiting-if waiting for timeout

 

You can create a future to describe the task in many ways. All the submit methods in executorservice will return a future, so as to submit a runnable or callable to the executor, and get a future to obtain the task execution result or cancel the task. You can also instantiate a futuretask for the runnable or callable specified by a task.

 

Description:
(01) runnablefuture is an interface that inherits the runnable and future interfaces. The source code of runnablefuture is as follows:

public interface RunnableFuture<V> extends Runnable, Future<V> {    void run();}

 

(02) futuretask implements the runnablefuture interface. Therefore, it also implements the future interface.

 

Part 1 examples and source code analysis

First, let's look at the basic usage of callable and future through an example, and then analyze the implementation principle of the example.

1 package COM. concurrency. taskexecution_6; 2 3 Import Java. util. concurrent. callable; 4 Import Java. util. concurrent. executionexception; 5 import Java. util. concurrent. executorservice; 6 Import Java. util. concurrent. executors; 7 Import Java. util. concurrent. future; 8 9/** 10 * callable and future implementation threads wait for 11 * @ classname: callablefuturetest12 * @ author xingle13 * @ date */15 public class callablefuturetest {16 17 public static void main (string [] ARGs) throws interruptedexception, executionexception {18 system. out. println ("START main thread"); 19 executorservice exec = executors. newfixedthreadpool (5); 20 21 // create a callable task and submit it to an executorservice. A future.22 callable <string> call = new callable <string> () {23 24 @ override25 Public String call () throws exception {26 system. out. println ("Start new thread"); 27 thread. sleep (5000); 28 system. out. println ("end new thread"); 29 return "some value"; 30} 31}; 32 33 future <string> task = exec. submit (CALL); 34 thread. sleep (1000); 35 task. get (); 36 // close thread pool 37 exec. shutdown (); 38 system. out. println ("end main thread"); 39} 40 41}

 

Execution result:

 

3.1 submit ()

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

1 Public <t> future <t> submit (callable <t> task) {2 if (task = NULL) throw new nullpointerexception (); 3 // create a runnablefuture object 4 runnablefuture <t> ftask = newtaskfor (task); 5 // execute "task ftask" 6 execute (ftask ); 7 // return "ftask" 8 return ftask; 9}

 

Note: Submit () creates 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);}

 

3.2 uretask 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 records the status of futuretask this. state = new; // ensure visibility of callable}

 

3.3 run () method of futuretask

Go back to the source code of submit.
After newtaskfor () creates an ftask object, the task is executed through execute (ftask. At this time, ftask is executed as a runnable object, and the run () method of ftask is called. The run () method of ftask is in Java/util/concurrent/futuretask. java implementation, the source code is as follows:

1 Public void run () {2 if (State! = New | 3! Unsafe. compareandswapobject (this, runneroffset, 4 null, thread. currentthread () 5 return; 6 try {7 // assign the callable object to C. 8 callable <v> C = callable; 9 If (C! = NULL & State = new) {10 V result; 11 Boolean ran; 12 try {13 // execute the call () method of callable and save the result to the result. 14 result = C. call (); 15 ran = true; 16} catch (throwable ex) {17 result = NULL; 18 ran = false; 19 setexception (Ex ); 20} 21 // if the operation is successful, save the result 22 if (RAN) 23 set (result); 24} 25} finally {26 runner = NULL; 27 // set "state flag" 28 int S = State; 29 If (S> = interrupting) 30 handlepossiblecancellationinterrupt (s); 31} 32}

 

Description: Run () will execute the call () method of the callable object, and finally save the result to the result, and save the result through set (result.
Call the get () method of futuretask and return the value saved through set (result.

Refer:

1. Chapter 6 task execution in Java concurrent programming practice

2. Java concurrent programming-executor framework

3. Java thread (7): callable and Future

 

Concurrent Programming-callable and Future

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.