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.

Output:

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.

Output:

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


Answers are detailed to be useful beyond job interviews. A few Q&As each day will make a huge difference in 3 to 24 months to go places depending on your experience.
Top