Created
June 16, 2016 07:41
-
-
Save rethab/7e6d4969fa6f0ee39ee8c5053f383573 to your computer and use it in GitHub Desktop.
Await.result doesn't cancel Futures on timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More background: https://github.com/semberal/semberal.github.io/blob/master/scala-future-timeout-patterns.md