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
import scala.concurrent.ExecutionContext.Implicits.global
val t = Future.firstCompletedOf( List(
Future {
1.to(10).foreach { int =>
println("1: " + int)
Thread.sleep(100)
}
"1"
},
Future {
1.to(10).foreach { int =>
println("2: " + int)
Thread.sleep(200) }
"2"
} ) )
t.onComplete(println(_))
This will show you the dangers of this approach. Instead, use a TimeoutScheduler. If you need a HashedWheelTimer implementation, checkout this one: https://github.com/ifesdjeen/hashed-wheel-timer
Written by Colin Dean
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Scala
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#