Does a Future get a new thread?

841 views Asked by At

Does a future implemented like below get a new thread? Apparently it is not(see the output below). Why? What should I do if I want my code to run on a new thread?

package MyTest

import com.twitter.util._

import scala.language.postfixOps

object Test {

  def test1 = Future {
    println("BeforeTest", Thread.currentThread())
    Thread.sleep(5000)
    println("AfterTest", Thread.currentThread())
  }

  def test2 = test1 onSuccess { case _ => println("Future on success") }

  def main(args: Array[String]): Unit = {

    println("main", Thread.currentThread())
    test2
    println("main123", Thread.currentThread())
  }
}

Output:

(main,Thread[run-main-0,5,run-main-group-0])

(BeforeTest,Thread[run-main-0,5,run-main-group-0])

(AfterTest,Thread[run-main-0,5,run-main-group-0])

Future on success

(main123,Thread[run-main-0,5,run-main-group-0])

2

There are 2 answers

2
Giovanni Caporaletti On BEST ANSWER

You are using twitter futures, not scala futures. Twitter futures are not multithreaded by default. You have to use a FuturePool (passing it an ExecutorService with your threadpool of choice)

Non-tested example (simple enough to work I hope :) ):

val executor = Executors.newFixedThreadPool(4)
val pool = FuturePool(executor)

def test1 = pool { 
  println("BeforeTest", Thread.currentThread())
  Thread.sleep(5000)
  println("AfterTest", Thread.currentThread())
}

def test2 = test1 onSuccess { case _ => println("Future on success") }

def main(args: Array[String]): Unit = {

  println("main", Thread.currentThread())
  test2
  println("main123", Thread.currentThread())

  executor.shutdown()
}
1
Jean-Philippe Pellet On

One of the interesting points of Futures is that you don't have to handle threads yourself. How they are executed depends entirely on the implicit ExecutionContext that is passed to the Future.apply() method (and other methods like map, flatMap, filter, etc.). A very gross implementation could create a new thread for each future being computed, but what mostly happens is that such code is executed by a pool of worker threads on the JVM.