Skip to content

Instantly share code, notes, and snippets.

@deanwampler
Last active March 28, 2021 13:44
Show Gist options
  • Save deanwampler/846425a8d4324db47b4b52770c9a6af3 to your computer and use it in GitHub Desktop.
Save deanwampler/846425a8d4324db47b4b52770c9a6af3 to your computer and use it in GitHub Desktop.
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.*
object FutureCF:
type Executable[T] = ExecutionContext ?=> T
// Compare Future.apply's signature:
// apply[T](body: => T)(implicit executor: ExecutionContext): Future[T]
def apply[T](body: => T): Executable[Future[T]] = Future(body)
def sleepN(dur: Duration): Duration =
val start = System.currentTimeMillis()
Thread.sleep(dur.toMillis)
Duration(System.currentTimeMillis - start, MILLISECONDS)
val future1 = FutureCF(sleepN(1.second))
val future2 = FutureCF(sleepN(1.second))(using global)
val duration1 = Await.result(future1, 2.seconds)
val duration2 = Await.result(future2, 2.seconds)
// REPL results for the last four lines:
// val future1: concurrent.Future[concurrent.duration.Duration] =
// Future(Success(1004 milliseconds))
// val future2: concurrent.Future[concurrent.duration.Duration] =
// Future(Success(1004 milliseconds))
// val duration1: concurrent.duration.Duration = 1004 milliseconds
// val duration2: concurrent.duration.Duration = 1004 milliseconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment