zoukankan      html  css  js  c++  java
  • notes for java 8 CompletableFuture

    https://www.callicoder.com/java-8-completablefuture-tutorial/

    CompletableFuture:

    Asynchronous programming -> non-blocking(task on a seperate thread, so main thread does not block) -> improves the performance of your programs.

    a future is used as a reference to the result of an asynchronous computation.
    isDone(): check whether the computation is done or not
    get(): retrieve the result of the computation

    Limitations of future:
    1. it cannot be manually completed
    2. you cannot perform further action on a Future's result without blocking.
       get() blocks until the result is available.
       You DON'T have the ability to attach a callback function to the Future and
       have it get called automatically when the Future's result is available.
       
    3. multiple futures cannot be chained together
    4. you can not combine multiple futures together
    5. no exception handling

    you can achieve all of the above with CompletableFuture.

    CompletableFuture implements Future and CompletionStage interface.

          
    1. Creating a CompletableFuture:

      CompletableFuture<String> completableFuture = new CompletableFuture<String>();
      String result = completableFuture.get();
     
      get() block until the Future is complete.
     
      completableFuture.complete("Future's Result"); // manually complete a Future
                                                     // all the clients waiting for this future will get the specified result.

    2. Running asynchronous computation using runAsync()

      run some background task asynchronously and don't want to return anything from the task,
      then you can use CompletableFuture.runAsync()
     
      It takes a Runnable object and returns CompletableFuture<Void>
     
      CompletableFuture<Void> future = CompulatableFuture.runAsync(new Runnable() {
        
        @Override
        public void run(){
          //simulate a long-running job
          ...
        }
      });
     
      future.get()  // block until the future to complete
     
     
      // lambda expression:
     
      CompletableFuture<Void> future = CompletableFuture.runAsync( ()-> {
         // simulate a long-running job
         ...
         System.out.println("i'll run in a separate thread than the main thread.");
      });
     
     
    3. Run a task asynchronously and return the result using supplyAsync()
       
       if you want to return some result from your background task:
       
       it takes a Supplier<T>, and returns CompletableFuture<T>
       
       CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
         @Override
         public String get() {
           ...
           return "Result of the asynchronous computation";
         }
       });
       
       String result = future.get();
       System.out.println(result);
       
       
       // lambda:
       CompletableFuture<String> future = CompletableFuture.supplyAysnc( () -> {
          ...
          return "...";
       });
       
       
    A Not about Executor and Thread Pool:
       
       ** CompletableFuture executes these tasks in a thread obtained from the global
       ForkJoinPool.commonPool()
       
       you can also create a Thread pool and pass it to runAsync() and supplyAsync()
       methods and let them execute their taks in a thread obtained from you thread pool
       
       CompletableFuture API has two variants:
         one which accepts an Executor as an argument and one which doesn't
         
       static CompletableFuture<Void> runAsync(Runnable runnable)
       static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
       static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
       static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
       
       create a thread pool and pass it to one of these methods:
       
       Executor executor = Executors.newFixedThreadPool(10);
       CompletableFuture<String> future = CompletableFuture.supplyAsync( () -> {
           ...
           return "...";
       }, executor);
       
        
      Transforming and acting on a CompletableFuture
      CompletableFuture.get() is blocking.   
     
      you can attach a callback to the CompletableFuture using thenApply(), thenAccept() and thenRun() method.
     
      1. thenApply()

  • 相关阅读:
    php遍历目录
    PHP处理一个5G文件,使用内存512M的,数据为整形,从大到小排序,优化排序算法
    百钱买百鸡问题 php版本
    青蛙跳100级台阶算法,完整可运行,php版本
    网站如何整体换角度
    SOA架构设计(转发)
    一些稍微复杂点的sql语句
    php变量和数组大小限制
    uploadify中文开发文档,解决php多图上传
    mysql索引的一些知识
  • 原文地址:https://www.cnblogs.com/bear129/p/10653669.html
Copyright © 2011-2022 走看看