Implementing asynchronous calls from Java future to guava Listenablefuture

Source: Internet
Author: User

Original address: http://blog.csdn.net/pistolove/article/details/51232004

Java Future

???? With executors, you can create different thread pools, some of which are commonly listed in the following table, and some of them may be. In practical applications, personal feelings primarily use newcachedthreadpook and newfixedthreadpool to create thread pools.

Executors Create line Cheng code
///Call the Newcachedthreadpool method, you can create a buffer thread pool, and in the modification method by the parameter to create a threadpoolexecutor, perhaps you would be very strange to return is a executorservice, How did you create a threadpoolexecutor?  Public StaticExecutorserviceNewcachedthreadpool() {return NewThreadpoolexecutor (0, Integer.Max_value, 60L, Timeunit.SECONDS,NewSynchronousqueue<runnable ());}//Threadpoolexecutor inherits the abstract service class Abstractexecutorservice Public classThreadpoolexecutorextendsAbstractexecutorservice {}//abstractexecutorservice implements the Executorservice interface Public Abstract classAbstractexecutorserviceImplementsExecutorservice {}//So Executorservice is actually the base class of Threadpoolexecutor, which explains
Executorservice (thread pool)

Executorservice is an interface that inherits the executor, adding a Submit method on top of the original Execute method, passing in a task that returns a future object that can get the results of an asynchronous calculation.

//ExecutorService继承了Executor,并扩展了新方法。publicinterfaceextends Executor { }//Executor中的方法voidexecute(Runnable command);//增加了submit方法,该方法传任务来获取Future对象,而Future对象中可以获取任务的执行结果submitsubmit(Runnable task);
Future (get asynchronous calculation results)

The future interface has the methods shown in the following table to get information about the tasks currently being performed.

Futuretask

The executor framework uses Futuretask to accomplish asynchronous tasks and can be used for any potential time-consuming calculations, generally futuretask for time-consuming computations, and the main thread can get results after completing its own tasks.

Futuretask wraps the callable and Runnable interface objects, provides the basic implementation of the future interface, starts, cancels the calculation, whether the query results are completed, and obtains the calculation results. The results are retrieved only when the calculation is complete, and the method blocks until the task is completed when the calculation is not completed. Once the calculation has been completed, the calculation cannot be restarted or canceled. Executed by the Excutor (thread pool), or by the thread object. If you need to do more time-consuming operations in the main thread, but do not want to block the main thread, you can hand these jobs to the future object in the background, when the main thread in the next need, you can get background job calculation results or execution status.

import Java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import Java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future; Public classtestfuture {//Create thread pool    Final StaticExecutorservice service = executors.Newcachedthreadpool(); Public Static void Main(string[] args)throwsInterruptedexception, executionexception {Long T1 = System.Currenttimemillis();//Task 1future<boolean> booleantask = service.Submit(NewCallable<boolean> () {@Override             PublicBooleanPager()throwsException {return true; }        }); while(true) {if(Booleantask.IsDone() &&!booleantask.iscancelled()) {//Simulation time-consumingThread.Sleep( -); Boolean result = Booleantask.Get(); System.Err.println("Booleantask:"+ result); Break; }        }//Task 2future<string> stringtask = service.Submit(NewCallable<string> () {@Override             PublicStringPager()throwsException {return "Hello World"; }        }); while(true) {if(Stringtask.IsDone() &&!stringtask.iscancelled()) {String result = Stringtask.Get(); System.Err.println("Stringtask:"+ result); Break; }        }//Task 3future<integer> integertask = service.Submit(NewCallable<integer> () {@Override             PublicIntegerPager()throwsException {return NewRandom ().Nextint( -); }        }); while(true) {if(Integertask.IsDone() &&!integertask.iscancelled()) {Integer result = Integertask.Get(); System.Err.println("Integertask:"+ result); Break; }        }//Execution TimeSystem.Err.println("Time:"+ (System.Currenttimemillis()-T1)); }}
Guava Future

Listenablefuture is a future that can be monitored, and it is an extension of the Java primitive future. The future represents an asynchronous computation task that can be computed when the task is completed. If you want the results to be displayed to the user or to perform additional calculations as soon as the calculation is complete, you must use another thread to continually query the state of the calculation. Doing so can make the code complex and inefficient. If you use Listenablefuture,guava to help detect if the future is complete, the callback function is automatically called if done, which reduces the complexity of concurrent programming.

Commonly used API1. Moreexecutors

This class is a tool class of the final type and provides a number of static methods. For example, the Listeningdecorator method initializes the Listeningexecutorservice method, and the Listenablefuture object is initialized with this instance of the Submit method.

2. Listeningexecutorservice

The class is an extension to Executorservice, re-executorservice the Submit method in the class, and returns the Listenablefuture object.

3. Listenablefuture

The interface extends the future interface and adds the AddListener method, which registers a listener on a given executor and invokes the listener immediately when the calculation is complete. You cannot ensure the order in which the listener executes, but you can make sure that it is called immediately when the calculation is complete.

4. Futurecallback

This interface provides the onsuccess and OnFailure methods. Gets the result of the asynchronous calculation and the callback.

5. Futures

This class provides a number of practical static methods for practical use.

6. Listenablefuturetask

This class extends the Futuretask class and implements the Listenablefuture interface, adding the AddListener method.

7.
 Public classTestListenableFuture2 {//Create thread pool    Final StaticListeningexecutorservice service = moreexecutors.Listeningdecorator(Executors.Newcachedthreadpool()); Public Static void Main(string[] args)throwsException {Long T1 = System.Currenttimemillis();//Task 1listenablefuture<boolean> booleantask = service.Submit(NewCallable<boolean> () {@Override             PublicBooleanPager()throwsException {return true;        }        }); Futures.Addcallback(Booleantask,NewFuturecallback<boolean> () {@Override             Public void onsuccess(Boolean result) {System.Err.println("Booleantask:"+ result); }@Override             Public void onfailure(Throwable t) {            }        });//Task 2listenablefuture<string> stringtask = service.Submit(NewCallable<string> () {@Override             PublicStringPager()throwsException {return "Hello World";        }        }); Futures.Addcallback(Stringtask,NewFuturecallback<string> () {@Override             Public void onsuccess(String result) {System.Err.println("Stringtask:"+ result); }@Override             Public void onfailure(Throwable t) {            }        });//Task 3listenablefuture<integer> integertask = service.Submit(NewCallable<integer> () {@Override             PublicIntegerPager()throwsException {return NewRandom ().Nextint( -);        }        }); Futures.Addcallback(Integertask,NewFuturecallback<integer> () {@Override             Public void onsuccess(Integer result) {Try{Thread.Sleep( -); }Catch(Interruptedexception e) {e.Printstacktrace(); } System.Err.println("Integertask:"+ result); }@Override             Public void onfailure(Throwable t) {            }        });//Execution TimeSystem.Err.println("Time:"+ (System.Currenttimemillis()-T1)); }}

Implementing asynchronous calls from Java future to guava Listenablefuture

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.