Java Multithreading: Callable,future,futuretask

Source: Internet
Author: User

First, futureThe future and callable are basically in pairs, callable is responsible for producing results, and the future is responsible for obtaining results. 1. The callable interface is similar to runnable, except that runnable has no return value. 2, callable task in addition to return the normal results, if an exception occurs, the exception will be returned, that is, the future can get the results of asynchronous execution of the task;3, the Future.get method will cause the main thread to block until the callable task execution is completed;The future is to cancel the execution result of the specific runnable or callable task, whether the query is completed, and the result is obtained. If necessary, the result of the execution can be obtained through the Get method, which blocks until the task returns the result.   the Future class is an interface:5 methods are declared in the future interface, which in turn explains the function of each method:
    • cancel method is used to cancel the task and returns true if the Cancel task succeeds, or False if the cancel task fails. The parameter mayinterruptifrunning indicates whether a task that is executing but not completed is allowed to be canceled, and if set to true, it means that the task in the process of execution can be canceled. If the task is completed, whether mayinterruptifrunning is true or FALSE, this method will definitely return false, that is, if canceling the completed task returns false, or if the task is executing, Returns True if the mayinterruptifrunning is set to true, or False if the mayinterruptifrunning is set to false, or if the task has not been executed, Returns true regardless of whether mayinterruptifrunning is true or false.
    • iscancelled method indicates whether the task was canceled successfully, and if it was canceled before the task was completed correctly, returns True
    • isdone method indicates whether the task has completed, and returns True if the task completes;
    • get () method is used to get the result of the execution, this method will be blocked and will wait until the task is completed before returning the execution result;
    • get (Long timeout, timeunit unit) is used to get execution results, if the result is not obtained within the specified time, Just throw the timeoutexception directly.

This means that the future offers three functions:

      • 1) Determine whether the task is completed;
      • 2) ability to interrupt tasks;
      • 3) Ability to get task execution results.
because the future is an interface, it is not directly used to create objects, Futuretask is a concrete implementation class. Two. FuturetaskRunnablefuture inherits the Runnable interface and the future interface, and Futuretask implements the Runnablefuture interface. So it can be executed as runnable by thread, and can get callable return value as future. Futuretask is an implementation class for the future interface. so it can be executed through the Excutor (thread pool), or it can be passed to the thread object. The executor framework uses Futuretask to accomplish asynchronous tasks and can be used to perform any potentially time-consuming calculations. The general Futuretask is used for time-consuming computations, and the main thread can get the results after completing its own tasks. Third, the actual caseFor example, now by invoking a method to get some results remotely, if it is the most traditional way of synchronization, the code is probably as follows:HASHMAP data = Getdatafromremote ();we will always wait for the return of Getdatafromremote () before we can continue the work behind it. This function is calculated from the remote data, if it takes a long time, and the latter part of the code is not related to the data, blocking here to wait for the result is a waste of time. So what can we do to improve it? the way to think about it is to return it immediately after calling the function, then proceed down, and then use the data again, or wait for the data. There are two ways to implement it, one is to use the future, and the other is to have a callbackusing the future
future getDataFromRemote2 (); // Do something HashMap data = (HASHMAP) future.get ();
GetDataFromRemote2 () initiates the acquisition of the result of the remote computation, while its own thread continues processing, knowing that the data will be acquired when needed
Private Future GetDataFromRemote2 () {    return threadpool.submit (new callable <HashMap>() {        publicthrows  Exception {            return  getdatafromremote ()        }    );}

Java Multithreading: Callable,future,futuretask

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.