notes for java 8 CompletableFuture

本文介绍Java 8中的CompletableFuture,一种用于非阻塞编程的工具,能提高程序性能。文章涵盖创建CompletableFuture的方法、运行异步计算任务、转换及操作CompletableFuture等关键概念。
Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

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()

转载于:https://www.cnblogs.com/bear129/p/10653669.html

您可能感兴趣的与本文相关的镜像

Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值