I am going to give you an introduction toparallelization. For this, I will be usingpar
.
However, you have to know, that to use this inScala 2.13+you need extra steps. You can read more onStackoverflow. I made the choice to still be using it because, I think, it is a great stepping stone to understand more complex subjects.
Let's dive in!
Compare the output of the twomap
. In the first one, you see the numbers in the same order they are in the sourceRange
. In the second one, the order is random, try running it several times ; you will see the order of the print statements change.
This happen because all the operation executed in themap
happen at thesametime, in parallel.
Remember the SKB onThread.sleep
, this was the introduction to the concept of Threads. To allow each operation to happen at the same time, Scala will manage a pool of threads for you. Each operation will be allocated to thread that the computer will compute and then return the result for each operation. Finally, the result will be combined before being returned to you.
In further SKBs, we are going to learn more about threads in more details. We are going to talk aboutFiber
,Future
,asynchronous
and more. Stay tuned!