Why Futures over Threads?

Reading Time: 2 minutes

Hola Amigo, have you ever wondered that when we can achieve concurrency or parallelism with threads, then what on Earth are other available options doing. Let’s have a closer look.

Threads: A unit of concurrency

Same old theory repeated once more,
“Threads are nothing but independent paths of execution. These can help in efficient use of the resources when used cautiously.”

What we can achieve using threads:
1. Concurrency if you have a single-core processor.
2. Parallelism if have multiple core processor.

But have you looked closely at the signature of the run() method?

void run();

Here return type is void, so you cannot expect anything in return, and have you ever encountered an exception in a child thread? How did you manage that?

So, we now have two things to take care of.

  • What if we want something in return from a thread.
  • What if an Exception occurs or some failure happens.

Futures: The newer version of threads

val computation = Future {
//do something in seperate thread.
}

Futures are nothing but the wrappers on the concurrent computations that are either going to be successful with a value or fail with an exception. These are just like a placeholder object for a value that may not yet exist. So unlike Threads,

  • Futures have a return type. For example, Future[Int] or Future[T] in the case of Scala.
  • Exceptions can be handled when a future completes with an exception.
  • Testing can be done without any hiccup because, in the end, we get a value for an assertion.
    If you want to learn more you can visit this blog or you can see the official documentation.

Conclusion

A very important aspect of writing any piece of code is it should be testable. And, Futures can be tested like any other method. Value returned by future computations can be used further. Exception handling is a vital part which a programmer cannot skip.

Thank you for scrolling.
See you next time.

Knoldus-blog-footer-image