Created
November 26, 2013 01:14
-
-
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 file contains hidden or 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
// 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") | |
} |
This file contains hidden or 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 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