14: ♥ Coding Scala Way – Scala concurrency with Future

Scala concurrency with Future explains step by step blocking vs unblocking calls and how implicit and apply concepts work under the covers. Scala extends the Java programming language and runtime in many ways, including concurrency where Scala version of Future<T> is more flexible than the Java version as you can create futures directly from blocks of code, and you can attach callbacks to futures for handling completions.

Scala Future – blocking call

Scala’s Future[T], resides in the “scala.concurrent” package, and it is container type, representing a computation that is supposed to eventually result in a value of type T. The simple “Future” demo code below blocks until execution finishes or timeout occurs in 5 seconds.


Scala Future – non-blocking call

“onComplete” method for non-blocking execution. “Await.result” is used to ensure that the main thread does not die before the “f” completes. “f” is a closure, which will be evaluated when needed i.e. f.onComplete {….}

The default JVM thread & spawned thread

The above code runs two threads. The “main” is a default thread created by the JVM. “ForkJoinPool-1-worker-5” is a worker thread spawned by a thread pool. “import scala.concurrent.ExecutionContext.Implicits.global” is used to obtain an implicit ExecutionContext. This global context is a default thread pool.


Create your own thread pool

Demystifying implicits & apply

The Future {….} is same as writing Future.apply {……}. The apply function is as shown below and applies the body of the function.

So, it can be written explicitly as

and then the future.onComplete method is like

Which can be written as


The following two tabs change content below.
Arulkumaran Kumaraswamipillai
Mechanical Engineer to freelance Java developer within 3 years. Freelancing since 2003 for the major banks, telecoms, retail & government organizations. Attended 150+ Java job interviews, and most often got 3-6 job offers to choose from. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training. Join my LinkedIn group. 1,350+ paid memberships.

By topics – 800+ Q&As ♥ Free ♦ FAQ

open all | close all

Java 200+ FAQs – Quick Brushup

open all | close all

100+ Java Tutorials step by step

open all | close all

13+ Tech Key Areas to standout

open all | close all

Java coding exercises

open all | close all