A brief explanation of Java's future programming pattern _java

Source: Internet
Author: User

The use of Java and contract friends may be future (interface) has been more familiar with, in fact, future itself is a widely used concurrent design patterns, to a large extent to simplify the need for data flow synchronization of concurrent application development. Future is supported in some domain languages, such as Alice ML, even directly at the grammatical level.

Here take Java.util.concurrent.Future as an example to simply say Future's specific work style. The future object itself can be considered an explicit reference, a reference to the result of the asynchronous processing. Because of its asynchronous nature, the objects it references may not be available at the beginning of creation (for example, in operations, in network transmissions, or in waiting). At this point, the program flow that gets future if you are not in a hurry to use the object referenced by future, it can do anything else that you want to do, and when the process goes to an object that needs to be referenced behind future, there may be two things:

Hope to see this object available and complete some related follow-up process. If it is not available, you can go to another branching process.
"Without you my life will lose meaning, so even if the lasting, I will wait until you." "(Of course, if there is no perseverance to wait, it is understandable to set a time-out)
In the former case, you can determine whether the referenced object is ready by calling Future.isdone () and take a different approach, and then simply call get () or
Get (long timeout, timeunit) waits for the object to be ready through a synchronous blocking mode. Whether the actual runtime is blocked or returned immediately depends on the timing of the call to get () and the order in which the object is ready.

In simple terms, the future model can meet data-driven concurrency requirements in a continuous process, with both performance gains for concurrent execution and simplicity and elegance in sequential processes.

Comparison with other concurrent design patterns
In addition to future, other common concurrent design patterns include "Callback Driver (multi-threaded environment)", "Message/Event driven (Actor model)", and more.

Callback is the most common asynchronous concurrency pattern, it has a high immediacy, simple interface design, and so on. But relative to future, its shortcoming is also very obvious. First, a callback in a multithreaded environment is typically executed in the module thread that triggers the callback, which means that the thread mutex problem is usually considered when writing the callback method, and second, that the provider of the callback mode interface is also relatively unsafe to perform user application callbacks in the thread of this module. Because you are not sure how long it will take or what is abnormal, it may indirectly result in this module's immediacy and reliability being affected; Furthermore, the use of callback interfaces is not conducive to sequential process development, since the execution of callback methods is isolated and it is difficult to converge with normal processes. Therefore, the callback interface is suitable for scenarios where simple tasks need to be completed in a callback and do not have to converge with other processes.

The drawback of these callback patterns is precisely future's forte. Since the use of Future is to drive the asynchronous data into a natural integration sequence, you do not have to consider the thread mutex problem at all, and Future can even be implemented in a single-threaded program model (see "Lazy Future", which will be mentioned below). On the other hand, the modules that provide the future interface do not have to worry about the reliability problems like the callback interface and the immediate impact that might have on the module.

Another common type of concurrent design pattern is "message (event) driven", which is generally used in the Actor model: a service requester sends a message to a service provider, and then continues the task of subsequent dependencies that do not depend on service processing, terminating the current process and logging the status before dependent results are required To trigger subsequent processes based on the state of the record when the response message is followed. The concurrency control based on state machine is more suitable for sequential process than callback, but the developer has to cut down the continuous process according to the invocation of asynchronous service to multiple state-differentiated sub-processes, which increases the complexity of the development artificially. This problem can be avoided by using the future pattern, which eliminates the need to break sequential processes for asynchronous invocation. It should be noted, however, that the Future.get () method may block the execution of a thread, so it is often not directly integrated into the regular actor model. (the Actor model based on the co-process can solve this conflict better)

Future's flexibility also manifests itself in its synchronous and asynchronous trade-offs, where developers can freely decide whether to wait [Future.isdone ()], when to wait [Future.get ()], and how long to wait [Future.get (timeout)], depending on the needs of the process. For example, depending on whether the data is ready or not, it is quite convenient to implement the "Asynchronous branch prediction" mechanism by using this gap to accomplish some other tasks.

The derivation of future
In addition to the basic forms mentioned above, future also has a wealth of derivative changes, and here are a few common ones.

Lazy Future
Unlike the general future, Lazy future does not actively start preparing the referenced object at the beginning of the creation, but waits until the object is requested to begin the work accordingly. Therefore, the Lazy future itself is not to achieve concurrency, but to save unnecessary computational resources as the starting point, the effect is similar to lambda/closure. For example, when designing some APIs, you may need to return a set of information, some of which can be computationally expensive. But the caller does not necessarily care about all of this information, so the objects that require more resources are provided in the form of Lazy future, which saves resources when the caller does not need to use specific information.

In addition lazy future can also be used to avoid unnecessary mutexes resulting from premature acquisition or locking of resources.

Promise
promise can be seen as a special branch of future, and common future are typically triggered directly by service callers, such as triggering processing immediately when a service is invoked or Lazy future values. However, promise is used to explicitly represent scenarios where asynchronous processes are not directly triggered by a service caller. For example, the future interface timing control, its asynchronous process is not by the caller, but by the system clock triggered, such as Taobao's distributed subscription framework provided by the future subscription interface, its waiting for the availability of data is not determined by the Subscriber, but the Publisher when publishing or updating data. As a result, a set () or fulfill () interface is generally more than the standard future,promise interface.

Reusable future
Conventional future are one-off, meaning that when you get an asynchronous processing result, the future object itself loses meaning. However, a specially designed future can also be reused, which is useful for data that can be changed multiple times. For example, the previously mentioned Taobao distributed subscription framework provides a future interface that allows multiple calls to the Waitnext () method (equivalent to Future.get ()), whether blocking each call depends on whether there is a data release after the last call, and if no updates are available, is blocked until the next data release. The advantage of this design is that the user of the interface can respond to the change of the subscription data in any suitable time or simply through an infinite loop in the independent thread, while also balancing other timed tasks and even waiting for multiple future. Examples of simplification are as follows:

for (;;) {
 schedule = Getnextscheduledtasktime ();
 while (Schedule > Now ()) {
  try {
   data = Subscription.waitnext (Schedule-now ());
   ProcessData (data);
  } catch (Exception e) {...}
 }}
 Doscheduledtask ();
}

The use of future
First, we enumerate a section of thinking in Java code, which is an example of the use of callable in concurrency, as follows:

: Concurrency/callabledemo.java import java.util.concurrent.*;

Import java.util.*;
 Class Taskwithresult implements callable<string> {private int id;
 public taskwithresult (int id) {this.id = ID;
 Public String called () {return ' result of Taskwithresult ' + ID; } public class Callabledemo {public static void main (string[] args) {Executorservice exec = Executors.newcachedthr
  Eadpool ();
  arraylist<future<string>> results = new arraylist<future<string>> ();
  for (int i = 0; i < i++) Results.add (Exec.submit (New Taskwithresult (i)));
   for (future<string> Fs:results) try {//get () blocks until Completion:System.out.println (Fs.get ());
    catch (Interruptedexception e) {System.out.println (e);
   Return
   catch (Executionexception e) {System.out.println (e);
   finally {Exec.shutdown (); }}/* Output:result of Taskwithresult 0 result of Taskwithresult 1 of Taskwithresult 2 ResulT of Taskwithresult 3 of Taskwithresult 4 of the result of Taskwithresult 5 of Taskwithresult of the result of TASKWITHR 

 Esult 7 Result of Taskwithresult 8 of Taskwithresult 9 *///:~

The

Explains the use of future, and first executorservice the Submit () method of the object exec invokes the future object, which is parameterized with a specific type of callable return result. You can use the Isdone () method to query whether future is finished. When the task completes, he has a result, and you can call the Get () method to obtain the result. You can also call get () directly without Isdone (), in which case the get () will block the knowledge that the results are ready. You can call the Get () function with a time-out, or call Isdone () to see if the task is complete, and then call Get ().

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.