0

Studying parallelism in Scala, I have got an impression that Futures and executor tasks are like lightweight threads. You can create more them than there are threads. But I get an OOM exception running the following code

import scala.concurrent.ExecutionContext.Implicits.global 
import scala.concurrent.{Future, future, Await}
import scala.concurrent.duration._

def fib(n: Int): Future[Int] = future {if (n < 2) n else 
  List(n-1, n-2) map fib map {Await.result(_, Duration.Inf)} sum}; 

Await.result(fib(35), Duration.Inf)

What is happening?

Little Alien
  • 1
  • 8
  • 22
  • 2
    What is your question? – Yuval Itzchakov Jun 27 '16 at 15:22
  • How many threads do you think this code is starting? – Dima Jun 27 '16 at 15:23
  • Each thread uses memory, so eventually you will run out. `ExecutionContext.Implicits.global` will spawn as lot of threads if you're not careful. – Michael Zajac Jun 27 '16 at 15:29
  • *How can using Futures exhaust system threads?* Each thread has overhead. You need a stack, JVM has a both of descriptors to allocate, etc. See [this](http://stackoverflow.com/questions/5483047/why-is-creating-a-thread-said-to-be-expensive) question. – Yuval Itzchakov Jun 27 '16 at 15:32
  • @m-z I see scaladoc saying *`ExecutionContext.global` is backed by a `ForkJoinPool`. I.e. it manages a limited amount of threads (known as parallelism level and set to the num of cores). The number of concurrently blocking computations can exceed the parallelism level only if each blocking call is wrapped inside a `blocking` call. Otherwise, there is a risk that the thread pool in the global execution context is starved, and no computation can proceed.* I read it like they say that new threads are not created by default. – Little Alien Jun 27 '16 at 15:52
  • Does my example demonstrate that `Await.result` contains a blocking block? I was sure that it releases the thread to handle other futures. – Little Alien Jun 27 '16 at 15:54
  • `Await.result` uses `blocking` underneath. – Michael Zajac Jun 27 '16 at 16:54

0 Answers0