Skip to content

Instantly share code, notes, and snippets.

@rethab
Created June 16, 2016 07:41
Show Gist options
  • Save rethab/7e6d4969fa6f0ee39ee8c5053f383573 to your computer and use it in GitHub Desktop.
Save rethab/7e6d4969fa6f0ee39ee8c5053f383573 to your computer and use it in GitHub Desktop.
Await.result doesn't cancel Futures on timeout
import java.util.concurrent.TimeUnit
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
/**
* Test if Futures are cancelled once the duration of
* the await has timed out.
*
* This demonstrates, that even after the 'Await.result'
* has timed out, the Future that it was waiting on still
* continues to run.
*
*
* Output:
* hello
* hello
* hello
* hello
* hello
* hello
* After await
* hello
* hello
* hello
*/
object CancellableFuture extends App {
import scala.concurrent.ExecutionContext.Implicits.global
Future {
val f = Future {
while (true) {
Thread.sleep(300)
println("hello")
}
}
try {
Await.result(f, Duration(2, TimeUnit.SECONDS))
} finally {
println("After await")
}
}
Thread.sleep(3000)
}
@rethab
Copy link
Author

rethab commented Jun 16, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment