Java asynchronous to synchronous listenablefuture in guava

Source: Internet
Author: User
Tags throwable

Listenablefuture's description

Concurrent programming is a challenge, but a powerful and simple abstraction can significantly simplify the writing of concurrency. With this in mind, guava defines the Listenablefuture interface and inherits the future interface under the JDK concurrent package, Listenablefuture allows you to register the callback method (callbacks), Called when the operation (multithreaded execution) is complete, or immediately after the operation (multithreaded execution) is completed. This simple improvement makes it possible to significantly support more operations, and such functionality is not supported in the future of JDK concurrent. In cases of high concurrency and requiring a large number of future objects, it is recommended to use Listenablefuture instead.

The underlying method in Listenablefuture is AddListener (Runnable, Executor), which executes the specified Executor in Runnable at the end of a multithreaded operation.

Creation and use of listenablefuture

Corresponding to the way in which the JDK Executorservice.submit (callable) submits a multithreaded asynchronous operation, Guava provides the Listeningexecutorservice interface, which returns Listenablefuture, and the corresponding Executorservice return to the normal future. Convert the Executorservice to Listeningexecutorservice, which can be decorated using moreexecutors.listeningdecorator (executorservice). To illustrate:

  

Listeningexecutorservice pool = moreexecutors.listeningdecorator (Executors.newfixedthreadpool (10));

Then we can submit the callable task to this listeningexecutorservice.

Final listenablefuture<string> future =  Pool.submit (new callable<string>() {            @Override              Public throws Exception {                thread.sleep (1000*3);                 return     " Task done! " ;            }        });

Then we add listener:

Future.addlistener (NewRunnable () {@Override Public voidrun () {Try {                        FinalString contents =Future.get ();                    SYSTEM.OUT.PRINTLN (contents); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }}}, Moreexecutors.samethreadexecutor ());

Let's take a look at the code above, it's really not elegant, we need to handle the thrown exception, we need to get the value from the previous calculation by Future.get (). Is there a more convenient way to do it? Of course, guava provides an easy way to replace the above:

New Futurecallback<string>() {                @Override                publicvoid  onsuccess (String Result) {                    System.out.println (result);                }                @Override                publicvoid  onfailure (Throwable t) {                    t.printstacktrace ();                }            });

The completion code is as follows:

Package Concurrency;import Com.google.common.util.concurrent.futurecallback;import Com.google.common.util.concurrent.futures;import Com.google.common.util.concurrent.listenablefuture;import Com.google.common.util.concurrent.listeningexecutorservice;import Com.google.common.util.concurrent.moreexecutors;import Java.util.concurrent.callable;import java.util.concurrent.executors;/** * Created by Hupeng on 2014/9/24. */public class Listenablefuturetest {public static void main (string[] args) throws Interruptedexception {Liste        Ningexecutorservice pool = moreexecutors.listeningdecorator (Executors.newfixedthreadpool (10)); Final listenablefuture<string> future = Pool.submit (new callable<string> () {@Override P                Ublic String Call () throws Exception {thread.sleep (1000 * 2);            Return "Task done!"; }});//Future.addlistener (new Runnable () {//@Override//Public void Run () {//try {//final String contents = Future.get ();// SYSTEM.OUT.PRINTLN (contents);//} catch (Interruptedexception e) {//E.P                    Rintstacktrace ();//} catch (Executionexception e) {//E.printstacktrace ();//        }//}//}, Moreexecutors.samethreadexecutor ()); Futures.addcallback (Future, New futurecallback<string> () {@Override public void onsuccess (STR            ing result) {System.out.println (result);            } @Override public void OnFailure (Throwable t) {t.printstacktrace ();        }        });  Thread.Sleep (5 * 1000);    Wait for Task done Pool.shutdown (); }}

Java asynchronous to sync listenablefuture in guava

Related Article

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.