Java multithreading: Future and FutureTask

Source: Internet
Author: User

The Executor framework uses Runnable as its basic task representation. Runnable is a restricted abstraction that can be written to logs or shared data structures, but cannot return a value. In fact, many tasks involve computing delays: Execute database queries, obtain resources from the network, or perform a complex and time-consuming computing. For such a task, Callable is a better abstraction. It can return a value and may throw an exception. Future indicates the 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. Copy the public interface Callable <V> {/*** Computes a result, or throws an exception if unable to do so. ** @ return computed result * @ throws Exception if unable to compute a result */V call () throws Exception ;} copy code copy code public interface Future <V> {/*** Attempts to cancel execution of this task. this attempt will * fail if the task has already completed, has already been canceled, * or cocould not Be canceled for some other reason. if successful, * and this task has not started when <tt> cancel </tt> is called, * this task shoshould never run. if the task has already started, * then the <tt> mayInterruptIfRunning </tt> parameter determines * whether the thread executing this task shocould be interrupted in * an attempt to stop the task. ** <p> After this method returns, subsequent callto {@ link # IsDone} will * always return <tt> true </tt>. subsequent callto {@ link # isCancelled} * will always return <tt> true </tt> if this method returned <tt> true </tt>. ** @ param mayInterruptIfRunning <tt> true </tt> if the thread executing this * task shoshould be interrupted; otherwise, in-progress tasks are allowed * to complete * @ return <tt> false </tt> if the task cocould not be canceled, * typically becaus E it has already completed normally; * <tt> true </tt> otherwise */boolean cancel (boolean mayInterruptIfRunning ); /*** Returns <tt> true </tt> if this task was canceled before it completed * normally. ** @ return <tt> true </tt> if this task was canceled before it completed */boolean isCancelled (); /*** Returns <tt> true </tt> if this task is completed. ** Completion may be due to normal termination, An exception, or * cancellation -- in all of these cases, this method will return * <tt> true </tt>. ** @ return <tt> true </tt> if this task completed */boolean isDone ();/*** Waits if necessary for the computation to complete, and then * retrieves its result. ** @ return the computed result * @ throws CancellationException if the computation was canceled * @ throws ExecutionException if the computa Tion threw an * exception * @ throws InterruptedException if the current thread was interrupted * while waiting */V get () throws InterruptedException, ExecutionException; /*** Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result, if available. ** @ param timeout the maximum time to wait * @ param unit the time unit of the timeout argument * @ Return the computed result * @ throws CancellationException if the computation was canceled * @ throws ExecutionException if the computation threw an * exception * @ throws InterruptedException if the current thread was interrupted * while waiting *@ throws TimeoutException if the wait timed out */V get (long timeout, timeUnit) throws InterruptedException, ExecutionException, TimeoutException ;} You can create a Future to describe the task by copying the code. The submit method in ExecutorService accepts a Runnable or Callable, and then returns a Future to obtain the task execution result or cancel the task. Copy the code/*** Submits a value-returning task for execution and returns a * Future representing the pending results of the task. the * Future's <tt> get </tt> method will return the task's result upon * successful completion. ** <p> * If you wowould like to immediately block waiting * for a task, you can use constructions of the form * <tt> result = exec. submit (aCallable ). get (); </tt> ** <p> Note: The {@ l Ink Executors} class except des a set of methods * that can convert some other common closure-like objects, * for example, {@ link java. security. privilegedAction} to * {@ link Callable} form so they can be submitted. ** @ param task the task to submit * @ return a Future representing pending completion of the task * @ throws RejectedExecutionException if the task cannot be * scheduled for execution * @ t Hrows NullPointerException if the task is null */<T> Future <T> submit (Callable <T> task ); /*** Submits a Runnable task for execution and returns a Future * representing that task. the Future's <tt> get </tt> method will * return the given result upon successful completion. ** @ param task the task to submit * @ param result the result to return * @ return a Future representing pending completion of t He task * @ throws RejectedExecutionException if the task cannot be * scheduled for execution * @ throws NullPointerException if the task is null */<T> Future <T> submit (Runnable task, T result);/*** Submits a Runnable task for execution and returns a Future * representing that task. the Future's <tt> get </tt> method will * return <tt> null </tt> upon <em> successful </em> completion. ** @ param task t He task to submit * @ return a Future representing pending completion of the task * @ throws RejectedExecutionException if the task cannot be * scheduled for execution * @ throws NullPointerException if the task is null */Future <?> Submit (Runnable task); copy the Code. In addition, newTaskFor (Callable <T> task) in ThreadPoolExecutor can return a FutureTask. Assume that we can obtain some computing results remotely using one method. Assume that the method is List getDataFromRemote (). If the synchronous method is used, the code is probably List data = getDataFromRemote (), we will wait until getDataFromRemote returns to continue the subsequent work. This function obtains the computing result remotely. If it takes a long time, if the subsequent code has nothing to do with this data, blocking there will waste a lot of time. How can we improve it ??? You can think of a way to obtain or wait for the data when you need to use the data. There are two methods for implementation: one is Future and the other is callback. Future <List> future = getDataFromRemoteByFuture (); // do something .... list data = future. get (); we can see that we return a Future object, and then our processing is followed by future. get () to obtain the value we want. That is to say, when getDataFromRemoteByFuture is executed, the remote computing result is obtained and its own thread continues to be executed without blocking. You can obtain the data again. Let's take a look at the implementation of getDataFromRemoteByFuture: copy the code private Future <List> getDataFromRemoteByFuture () {return threadPool. submit (new Callable <List> () {@ Override public List call () throws Exception {return getDataFromRemote ();}});} to copy the code, we call the getDataFromRemote method in this method and use the thread pool. After a task is added to the thread pool, the Future object is returned. You can also pass in a timeout parameter to the get method of Future to set the wait time. You can also use FutureTask to obtain the result: copy the code FutureTask <List> futureTask = new FutureTask <List> (new Callable <List> () {@ Override public List call () throws Exception {return getDataFromRemote () ;}}); threadPool. submit (futureTask); futureTask. get (); the copy code FutureTask is a specific implementation class. The ThreadPoolExecutor's submit method returns a Future implementation, which is a specific instance of FutureTask, futureTask helps to execute specific tasks and associate them with the get method in the Future interface. In addition to helping ThreadPool implement the Future support for tasks added to the thread pool, FutureTask also provides us with great convenience, so that we can also support Future job scheduling.

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.