CompletableFuture常用方法总结


CompletableFuture常用方法总结

下文对CompletableFuture类中的常用方法进行了总结,以备不时之需;

创建方法

示例

  1. supplyAsync()
fun supplyAsync() {
    val future = CompletableFuture.supplyAsync {
        return@supplyAsync FutureTask.printlnWithString()
    }
    val result = future.get();
    println("main thread result:$result")
}
  1. runAsync()
    fun runAsync() {
        val future = CompletableFuture.runAsync {
//            return@runAsync printlnWithString()
            FutureTask.printlnWithVoid()
        }
        val result = future.get();
        //返回结果为null
        println("main thread result:$result")
    }
  1. completedFuture()
/**
 * 返回设定值,不会启用线程池去提交任务
 */
fun completedFuture() {
    val future = CompletableFuture.completedFuture {
        return@completedFuture FutureTask.printlnWithString()
    }
    val result = future.get();
    //返回结果为null
    println("main thread result:$result")
}

特点:

方法名 描述 是否返回结果 返回异常 同组方法
supplyAsync supplyAsync提交任务 返回结果 抛出ExecutionException supplyAsync(Runnable runnable, Executor executor)
runAsync runAsync提交任务 无返回结果 抛出ExecutionException runAsync(Runnable runnable, Executor executor)
completedFuture 设置默认返回值 返回结果 不会抛出异常

指定线程执行

supplyAsync
runAsync

链式调用

示例

  1. thenApply()
fun thenApply() {
    val fn = FutureTask.create_future()
    //将fn的结果传递到consumer_future函数中
    val fn2 = fn.thenApply { fn_result -> FutureTask.consumer_future(fn_result) }
    fn2.get()
}
  1. thenAccept()
fun thenAccept() {
    val fn = FutureTask.create_future()
    val fn2 = fn.thenAccept { fn_result -> FutureTask.consumer_future(fn_result) }

    val fn2Result = fn2.get()
    println("fn2Result:$fn2Result");
}
  1. thenRun()
fun thenRun() {
    val fn = FutureTask.create_future()
    val fn2 = fn.thenRun() { println("fn_result:" + Thread.currentThread().name) }

    val fn2Result = fn2.get()
    println("fn2Result:$fn2Result");
}
  1. thenCompose()
fun thenCompose() {
    val fn = FutureTask.create_future()
    val fn2 = fn.thenCompose { fn_result -> FutureTask.consumer_future(fn_result) }

    val fn2Result = fn2.get()
    println("fn2Result:$fn2Result");
}
  1. exceptionally()
fun exceptionally() {
    val fn = FutureTask.create_future_exception()
    val fn2 = fn.exceptionally { ex ->
        var threadName = Thread.currentThread().name
        println("thread_name:$threadName,异常堆栈为:" + ex.message)
        "返回错误信息"
    }

    val fn2Result = fn2.get()
    println("fn2Result:$fn2Result");
}
  1. whenComplete()
    fun whenComplete() {
        val fn = FutureTask.create_future()
//        val fn = FutureTask.create_future_exception()
        val fn2 = fn.whenComplete { fn_result, ex ->
            var threadName = Thread.currentThread().name

            if (ex == null) {
                println("thread_name:$threadName,fn执行成功,返回结果为:$fn_result")
            }

            if (ex != null) {
                println("thread_name:$threadName,fn执行失败,异常堆栈为:" + ex.message)
            }
        }

        val fn2Result = fn2.get()
        println("fn2Result:$fn2Result");
    }
  1. handle()
fun handle() {
        val fn = FutureTask.create_future()
//        val fn = FutureTask.create_future_exception()
        val fn2 = fn.handle { fn_result, ex ->
            var threadName = Thread.currentThread().name

            if (ex == null) {
                println("thread_name:$threadName,fn执行成功,返回结果为:$fn_result")
            }

            if (ex != null) {
                println("thread_name:$threadName,fn执行失败,异常堆栈为:" + ex.message)
            }
            return@handle "handle执行完成"
        }

        val fn2Result = fn2.get()
        println("fn2Result:$fn2Result");
    }

特点:

方法名 描述 是否返回结果 返回异常 同组方法
thenApply fn2处理fn1的处理结果,适用于结果转换 返回结果 抛出ExecutionException thenApplyAsync(Function action, Executor executor)
thenAccept fn2处理fn1的处理结果 无返回结果 抛出ExecutionException thenAcceptAsync(Function action, Executor executor)
thenRun fn执行完成后执行Runnable,不关心fn的返回值 抛出ExecutionException thenRunAsync(Runnable action,Executor executor)
thenCompose fn执whenComplete 返回fn同类型的返回值 抛出ExecutionException thenComposeAsync(Function action, Executor executor)
exceptionally 用于处理fn的异常 有返回值 抛出ExecutionException thenComposeAsync(Function action, Executor executor)
whenComplete 处理fn返回的结果或者执行异常 有返回值 抛出ExecutionException whenComplete(Function action, Executor executor)
handle() 处理fn返回的结果或者执行异常 无返回值 抛出ExecutionException handleAsync(Function action, Executor executor)

需要注意的是thenApplythenCompose的区别:

  1. thenApply返回的是CompletableFuture对象,thenCompose的返回值与fn原有的返回值

组合

示例

  1. allOf()
fun allOf() {
    val allFuture = CompletableFuture.allOf(
        FutureTask.create_future(),
        FutureTask.create_future_time3s(),
        FutureTask.create_future_exception()
    )
    val result = allFuture.get()
    println("main result:$result")
}
  1. thenCombine()
fun thenCombine() {
    val combine = FutureTask.create_future().thenCombine(FutureTask.create_future_time3s()) { r1, r2 ->
        println("BiFunction threadName:" + Thread.currentThread().name)
        "fn1的result:$r1,fn2的result:$r2,"
    }

    val combineResult = combine.get()
    println("main thread result:$combineResult")
}
  1. thenAcceptBoth()
fun thenAcceptBoth() {
    val combine = FutureTask.create_future().thenAcceptBoth(FutureTask.create_future_time3s()) { r1, r2 ->
        println("BiFunction threadName:" + Thread.currentThread().name + ",fn1的result:$r1,fn2的result:$r2,")
    }

    val thenAcceptBothResult = combine.get()
    println("main thread result:$thenAcceptBothResult")
}
  1. runAfterBoth()
fun runAfterBoth() {
    val combine = FutureTask.create_future().runAfterBoth(FutureTask.create_future_time3s()) {
        println("Runnable threadName:" + Thread.currentThread().name)
    }

    val thenAcceptBothResult = combine.get()
    println("main thread result:$thenAcceptBothResult")
}
  1. applyToEither()
fun applyToEither() {
    val combine = FutureTask.create_future().applyToEither(FutureTask.create_future_time3s()) { r1 ->
        println("Runnable threadName:" + Thread.currentThread().name + ",fn1或fn2执行结果为$r1")
        r1
    }

    val thenAcceptBothResult = combine.get()
    println("main thread result:$thenAcceptBothResult")
}
  1. acceptEither()
fun acceptEither() {
    val combine = FutureTask.create_future().acceptEither(FutureTask.create_future_time3s()) { r1 ->
        println("Runnable threadName:" + Thread.currentThread().name + ",fn1或fn2执行结果为$r1")
    }

    val thenAcceptBothResult = combine.get()
    println("main thread result:$thenAcceptBothResult")
}
  1. runAfterEither()
fun runAfterEither() {
    val combine = FutureTask.create_future().runAfterEither(FutureTask.create_future_time3s()) {
        println("Runnable threadName:" + Thread.currentThread().name)
    }

    val thenAcceptBothResult = combine.get()
    println("main thread result:$thenAcceptBothResult")
}

特点:

方法名 描述 是否返回结果 同组方法
allOf 组合多个Future 无结果 anyOf:入参为可变数组或数组
thenCombine 将fn1的结果和fn2的结果传递到BiFunction中 有返回值为BiFunction thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor)
thenAcceptBoth fn1的结果和fn2的结果传递到BiFunction中 无返回值 thenAcceptBothAsync
runAfterBoth fn1执行完成后执行fn2,然后执行Runnable执行线程默认为fn2的执行线程 无返回值 runAfterBothAsync(CompletionStage<?> other,Runnable action)
applyToEither 将fn1的结果和fn2的结果,二者任一一个结果传递到Function中 有返回值为BiFunction applyToEitherAsync(CompletionStage<? extends U> other,Function<? super T, U> fn,Executor executor)
acceptEither fn1或fn2执行完成,执行fn3 无返回值 acceptEitherAsync
runAfterEither fn1或fn2执行完成,执行fn3 无返回值 runAfterEitherAsync

需要注意的是thenCombineapplyToEither的区别:

  1. thenCombine是两个fn都完成后才执行fn3,applyToEither是任一一个fn完成后就执行fn3

获取结果

示例

  1. get()
fun get() {
    val future = FutureTask.create_future()
    val result0 = future.get()

    val future_exception = FutureTask.create_future_exception()
    val result1 = future_exception.get()
}
  1. join()
fun join() {
    val future = FutureTask.create_future()
    var list = ArrayList<String>()
    list.add("1")

    list.forEach { item ->
        val result0 = future.join()
        println("result0:$result0,item:$item")
    }


    val future1 = FutureTask.create_future_exception()
    future1.join()
}
  1. getNow()
fun getNow() {
    val future = FutureTask.create_future_time3s()
    val result = future.getNow("defaultValue")
    println("create_future_time3s result:$result")

    val future1 = FutureTask.create_future_exception()
    TimeUnit.SECONDS.sleep(1)
    future1.getNow("exception")
}
  1. isDone()
fun isDone(){
    val future = FutureTask.create_future_time3s()
    val done = future.isDone
    println("future是否完成:$done")
}

特点:

方法名 描述 是否支持lambda调用
get 阻塞的方式获取结果 不支持lambda方式进行调用
join 阻塞的方式获取结果 支持lambda方式进行调用
getNow 立即尝试获取结果,如果future未完成就返回默认值,非阻塞的方式 不支持lambda方式进行调用
isDone 判断是否执行完成 支持lambda方式进行调用

  TOC