Java multithreading: Callable, Future, FutureTask, and callablefuturetask

Source: Internet
Author: User

Java multithreading: Callable, Future, FutureTask, and callablefuturetask
1. FutureFuture and Callable are usually displayed in pairs. Callable is responsible for generating results, and Future is responsible for obtaining results. 1. The Callable interface is similar to Runnable, but Runnable does not return a value. 2. In addition to the normal results returned by the Callable task, if an exception occurs, the Callable task will also be returned, that is, Future can get various results of the asynchronous execution task; 3. Future. the get method will cause the main thread to block until the Callable task is completed. The Future method cancels the execution results of a specific Runnable or Callable task, queries whether the query is complete, and obtains the results. If necessary, you can use the get method to obtain the execution result. This method is blocked until the task returns the result. The Future class is an interface: five methods are defined in the Future interface. The following explains the role of each method in sequence:

  • The cancel method is used to cancel a task. if the task is canceled successfully, true is returned. If the task fails to be canceled, false is returned. The mayInterruptIfRunning parameter indicates whether to cancel a task in progress but not completed. If it is set to true, the task in progress can be canceled. If the task has been completed, no matter whether mayInterruptIfRunning is true or false, false is returned for this method, that is, false is returned if the task has been canceled; if the task is being executed, if mayInterruptIfRunning is set to true, true is returned. If mayInterruptIfRunning is set to false, false is returned. If the task has not been executed, true is returned regardless of whether mayInterruptIfRunning is true or false.
  • The isCancelled method indicates whether the task is successfully canceled. if the task is successfully canceled before it is completed, true is returned.
  • The isDone method indicates whether the task has been completed. if the task is completed, true is returned;
  • The get () method is used to obtain the execution result. This method is blocked and will not return the execution result until the execution of the task is completed;
  • Get (long timeout, TimeUnit unit) is used to obtain the execution result. If the result is not obtained within the specified time, the TimeoutException is directly thrown.

That is to say, Future provides three functions:

    • 1) Determine whether the task is completed;
    • 2) the task can be interrupted;
    • 3) obtain the task execution result.
Because Future is an interface, it cannot be used directly to create objects. FutureTask is a specific implementation class. Ii. FutureTask RunnableFuture inherits the Runnable and Future interfaces, while FutureTask implements the RunnableFuture interface. Therefore, it can be executed by the thread as Runnable and the return value of Callable as the Future. FutureTask is an implementation class of the Future interface. Therefore, it can be executed through Excutor (Thread pool) or passed to the Thread object for execution. The Executor framework uses FutureTask to complete asynchronous tasks and can be used for any potentially time-consuming computing. Generally, FutureTask is mostly used for time-consuming computing. The main thread can obtain the result after completing its own task. 3. In actual cases, for example, you can call a method to remotely obtain some computing results. For the most traditional synchronization method, the code is roughly as follows: HashMap data = getDataFromRemote (); we will wait until the getDataFromRemote () is returned before continuing the subsequent work. This function is used to remotely obtain the computing results of data. If it takes a long time and the code that follows is irrelevant to the data, blocking is a waste of time to wait for the result. So how can we improve it? The method that can be thought of is to call the function and return immediately, and then continue to execute it. It will be used again when the data needs to be used, or wait for the data again. There are two methods to implement it. One is to use ure, and the other is to use Future for callback.
Future<HashMap> future = getDataFromRemote2();//do somethingHashMap data = (HashMap) future.get();
GetDataFromRemote2
private Future<HashMap> getDataFromRemote2() {    return threadpool.submit(new Callable<HashMap>() {        public HashMap call() throws Exception {            return getDataFromRemote()        }    });}

 

 

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.