Last Updated: July 15, 2016
· colindean

Don't use Future.firstCompletedOf with two futures for timeouts

Do not create two futures expecting one to act as a timeout with a Thread.sleep. If the real operation completes, the timeout future will continue running. If you do this a lot, you will exhaust your thread pool on timeout futures blocking threads.

import scala.concurrent.Future
val t = Future.firstCompletedOf( List(
  Future { { int =>
      println("1: " + int)
  Future { { int =>
      println("2: " + int)
      Thread.sleep(200) }
  } ) )

This will show you the dangers of this approach. Instead, use a TimeoutScheduler. If you need a HashedWheelTimer implementation, checkout this one: