Thread vs CompletableFuture

后端 未结 3 856
無奈伤痛
無奈伤痛 2021-01-31 09:56

What is the advantage of passing code directly to thread vs using CompletableFuture instead?

Thread thread = new Thread(() -> {do something});
thread.start()         


        
3条回答
  •  悲&欢浪女
    2021-01-31 10:30

    CompletableFuture.runAsync(...) runs the Runnable in the forkJoin-Pool which is managed, while new Thread() creates a new thread which you have to manage.

    What does "is managed" mean, it's pre-allocated and the threads are shared in the JVM. When the runnable is completed, the thread can be reused for other runnables. This makes better usage of resources, especially as thread instantiation is an expensive operation - not only the object, but also some extra non-heap memory - the thread stack - has to be allocated.

提交回复
热议问题