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

overall bird-eye view of the Java Environment together with so many useful questions. I am totally impressed with the way you have learned Java.

Yours Sincerely
Ye Tun Oo ( More )

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.

Posted in Scala way of coding

800+ Java Interview Q&As – ♥Free | ♦FAQs

open all | close all

Pressed for time? 200+ Java Interview FAQs

open all | close all

16 Technical Key Areas to be a top-notch

open all | close all

100+ Java Tutorials – Step by step

open all | close all

100+ Java Coding Exercises

open all | close all

How good are your

open all | close all