What is the difference between "Future.successful(None)" and "Future(None)"

10,415

Solution 1

Future.apply(None) creates asynchronous computation and executes it. It means that extra lambda object is created and extra task is scheduled (however trivial task).

Future.successful(None) just produces already completed future. It is more efficient.

Solution 2

I don't think that Future(None) gives a big overhead, but still in it's default implementation each call to apply spawns a new task for a ForkJoin thread pool, whereas Future.successful(None) completes immediately. And each call to map or flatMap on the future creates a new task for the poll, which also gives some overhead, so you might want to take a look at scalaz Future/Task implementation which handles such details more carefully.

Share:
10,415
Amir Karimi
Author by

Amir Karimi

I write code and build stuff.

Updated on June 07, 2022

Comments

  • Amir Karimi
    Amir Karimi almost 2 years

    Future.apply starts an asynchronous computation whereas Future.successful creates an already completed Future with the specified result.

    Now is Future(None) (Future.apply(None)) less efficient than Future.successful(None)?

  • Fatih Donmez
    Fatih Donmez almost 8 years
    Can you give same real world example for Future.successful? I can't understand why we need that, except then existing interface waiting Future[T] and we want to pass some Future with already known result?
  • Casey
    Casey almost 7 years
    @FatihDonmez That's essentially the use case, yes. Why write two separate interfaces when you can just wrap the known values?