Simple and future pattern

Source: Internet
Author: User
Simple and future patternJune 24, 2013 small Wuge comments Read comments

A few days ago to see the code of HDFs QJM, inside see a listenablefuture, to tell the truth for Java, I still just by looking at the code, met not see the way to check again, it is really no time and energy to read the entire article such as "Thinking in Java" Such a big brick, now such a way, should be enough for now. The emphasis is on systems and business, and the language itself should not be an obstacle. Back to the listenablefuture, on the internet to look at the relevant information, the ins and outs of its understanding, here to record.

The listenablefuture mentioned earlier is a module in Google's own Java Library guava (http://code.google.com/p/guava-libraries/), It itself is a future of Java. Strictly speaking, future is a kind of design pattern, it has no relation with language. The latest c++11, also joined the future support, but I wrote C + + before, C++11 has not officially released, plus it is relatively new, mainstream compiler support itself is not very good, so just know it exists, and did not go to study what it is doing, how to use. Next, I will introduce the future and its usage step-by-step through some examples of Java future.

In short, future is a pattern: it means ' future (future) ', you submit an asynchronous task, such as submitting to a threadpool, and at the same time getting a future object, the execution of the task is asynchronous, At this point you can do other things, and when the asynchronous task is over, you can get the result of the task asynchronously executed through the future object. The following is a simple example to intuitively feel the future:

1
2
3
4
5
6
7 8 9
30 (a) (a)
Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;ImportJava.util.concurrent.Future;ImportJava.util.concurrent.FutureTask; Public classfuturetest { Public Static voidMain (string[] args) {Executorservice executor = Executors.newfixedthreadpool (1); future< string> Future = Executor.submit (Newcallable< string> () { PublicString Call () { return"Hello futue!"; }
    });Try{thread.sleep (1000);
    System.out.println (Future.get ()); }Catch(Interruptedexception e) {Future.cancel (true); }Catch(Executionexception e) {Future.cancel (true); }finally{Executor.shutdown (); }
  }
}

In the above program, and I noticed the 20th line of Thread.Sleep (1000), where the original meaning is that during the execution of the asynchronous task, the original thread can do anything and will not block. The sleep is simple here, but the meaning to be expressed is clear.

Looking at the example above, careful friends always have such a question, future to get the results of asynchronous task execution, need to poll or blocking the waiting way, such a way, always appear not too ' Perfect ', we know, the better way, should be asynchronous execution is over, automatically notifies the user that the asynchronous task is over, and you can get the execution result by future. This is the birth of Google's listenablefuture, users can register a callback function and provide a thread pool (optional), when the asynchronous task execution is completed, it will automatically in the user-supplied line Cheng Chili call the user registered callback function, notify the user asynchronous task execution is over. Of course, if the user does not provide a thread pool, it runs the callback function in the worker thread that is running the asynchronous task, which is appropriate for the task of the worker thread itself, which is lighter. Here are a few examples to illustrate the specific uses of listenablefuture:

1
2
3
4
5
6
7 8 9
30 (a) (a)
the
37
Importjava.util.concurrent.Callable;ImportJava.util.concurrent.ExecutionException;ImportJava.util.concurrent.Executors;ImportCom.google.common.util.concurrent.Futures;ImportCom.google.common.util.concurrent.ListenableFuture;ImportCom.google.common.util.concurrent.ListeningExecutorService;ImportCom.google.common.util.concurrent.MoreExecutors; Public classlistenablefuturetest { Public Static voidMain (string[] args) {Listeningexecutorservice executor = Moreexecutors.listeningdecorator (executors.newfixed ThreadPool (1));Finallistenablefuture< string> future = Executor.submit (Newcallable< string> () { PublicString Call ()throwsException { return"Hello listenable Future";
 
    }
    }); Future.addlistener (NewRunnable () { Public voidRun () {Try{System.out.println (Future.get ()); }Catch(Interruptedexception e) {Future.cancel (true); }Catch(Executionexception e) {Future.cancel (true);
 
    }}, Executors.newfixedthreadpool (1));
  System.out.println ("Exit ..."); }
}

In the above program, the 35th line of System.out.println ("Exit ..."); May be preceded by the "Hello listenable Future" Print to stdout, which indirectly indicates that the execution of the callback function is in another thread. In addition, in the above example, we find that users need to handle interruptedexception and Executionexception in a registered callback function, which is a bit of a hassle. Here guava also provides another way to use, the interface to see more clearly, the following is an example of the use of this method:

1
2
3
4
5
6
7 8 9
30 (a) (a)
at
36
Importjava.util.concurrent.Callable;ImportJava.util.concurrent.Executors;ImportCom.google.common.util.concurrent.FutureCallback;ImportCom.google.common.util.concurrent.Futures;ImportCom.google.common.util.concurrent.ListenableFuture;ImportCom.google.common.util.concurrent.ListeningExecutorService;ImportCom.google.common.util.concurrent.MoreExecutors; Public classListenableFutureTest2 { Public Static voidMain (string[] args) {Listeningexecutorservice executor = Moreexecutors.listeningdecorator (executors.newfixed ThreadPool (1));Finallistenablefuture< string> future = Executor.submit (Newcallable< string> () { PublicString Call ()throwsException { return"Hello listenable Future";
 
    }
    }); Futures.addcallback (Future,Newfuturecallback< string> () { Public voidonsuccess (String result) {System.out.println (result); }k Public voidOnFailure (Throwable t) {System.out.println ("error:" + t);
 
    }, Executors.newfixedthreadpool (1));
  System.out.println ("Exit ..."); }
}

In the above examples, the user thread pool is explicitly provided to perform the callback function. The user can also not provide a thread, or can Cheng the current line through Moreexecutors.samethreadexecutor () to perform the return function.

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.