简体   繁体   中英

Is there an overhead because of nesting Futures

I wrote this code

package com.abhi
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global

object FutureNesting extends App {

   def measure(future: => Future[Unit]) : Future[Long] = {
      val start = System.currentTimeMillis()
      val ec = implicitly[ExecutionContext]
      val t = future
      t map { case _ =>
         val end = System.currentTimeMillis()
         end - start
      }
   }

   measure(Future{ Thread.sleep(10000) }) onSuccess {case a => println(a)}
   scala.io.StdIn.readLine()
}

So how many threads am I using in this code. The broader question is that what is the impact of going on nesting future inside futures.

So I ran the application above and observed it using Visual VM. This is what I saw

在此处输入图片说明

So the application launched 2 threads ForkJoinPool-1-worker-5 and ForkJoinPool-2-worker-3. However it launches the same 2 threads even if I remove the nesting. So I am not sure what is the overhead because of nesting the futures like above.

Edit:: Some people said it depends on the type of ThreadPool (ForkJoin etc).

I won't know what type of pool do Akka.HTTP or Spray use? I planned to use a code snippet similar to the one above in a Spray web service. The idea was to measure the performance of the web service using Futures.

In your case, you are using wrap over thradpool (ForkJoingPool from java.util.concurrent). Of course, all Futures are executed in it.

 import scala.concurrent.ExecutionConext.Implicits.global

Based on this you must implicitly instantiate pool instead import, like this:

implicit val ec: ExecutionContext

And use method from ForkJoinPool: getActiveThreadCount()

Second approach: You can open profiler (like JProfiler - from Jetbrains or Jvisualvm - attached with jdk) and watch meta information including threads parameters like their amount, activity, memory usage and etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM