Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a Future get a new thread?

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])

like image 940
Jonna Avatar asked May 24 '26 19:05

Jonna


1 Answers

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()
}
like image 129
Giovanni Caporaletti Avatar answered May 26 '26 13:05

Giovanni Caporaletti