Skip to content

Instantly share code, notes, and snippets.

@TomasMikula
Created November 26, 2013 01:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TomasMikula/7651866 to your computer and use it in GitHub Desktop.
Save TomasMikula/7651866 to your computer and use it in GitHub Desktop.
lazily { expr }: Scala lazy vals that can be checked for having been evaluated. It is adapted from this StackOverflow answer: http://stackoverflow.com/a/17057490/1572599
// This example defines an implicit ExecutionContext
// that is instantiated only when necessary.
// If it was instantiated, it is shutdown at the end.
import java.util.concurrent.Executors
import scala.concurrent.{ ExecutionContext, Future }
import Lazy._
val executorService = lazily {
println("INITIALIZING THREAD POOL")
val threadPool = Executors.newFixedThreadPool(10)
ExecutionContext.fromExecutorService(threadPool)
}
implicit def executionContext: ExecutionContext = executorService
// non-deterministic computation that
// may or may not need an Execution context
if(math.random < 0.5)
Future { println("ASYNCHRONOUS COMPUTATION") }
if(executorService.isEvaluated) {
println("THREAD POOL SHUTDOWN")
executorService.shutdown()
}
else {
println("THREAD POOL NEVER INITIALIZED")
}
import scala.language.implicitConversions
object Lazy {
def lazily[A](f: => A): Lazy[A] = new Lazy(f)
implicit def evalLazy[A](l: Lazy[A]): A = l()
}
class Lazy[A] private(f: => A) {
private var option: Option[A] = None
def apply(): A = option match {
case Some(a) => a
case None => val a = f; option = Some(a); a
}
def isEvaluated: Boolean = option.isDefined
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment