Created
January 9, 2013 12:45
-
-
Save sofoklis/4492880 to your computer and use it in GitHub Desktop.
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
package org.example | |
import scala.concurrent.{ Future, Promise, future, promise } | |
import scala.concurrent.ExecutionContext.Implicits.global | |
class FuturesAndPromises | |
object FuturesAndPromises { | |
def main(args: Array[String]) { | |
futureSample | |
println | |
println | |
promiseSample | |
} | |
private def futureSample: Unit = { | |
println("Future sample starts") | |
// Create a future with a likely long time of completion | |
val f: Future[String] = future { | |
for (i ← 1 to 1000000) {} | |
// You can throw an exception which will call the onComplete and onFailure callbacks | |
//throw new IllegalArgumentException("Something wrong") | |
// Or you can return a proper value which will call the onComplete and onSuccess callbacks | |
"Sofoklis" | |
} | |
registerCallbacks(f) | |
println("Future loop start") | |
for (i ← 1 to 10000000) {} | |
println("Future Sample exit") | |
} | |
private def promiseSample: Unit = { | |
println("Promise Sample starts") | |
// Create a promise | |
val p: Promise[String] = promise[String] | |
// Get the associated future | |
val f = p.future | |
registerCallbacks(f) | |
// you complete the future by | |
p success "Sofoklis" | |
// or by, note that for a specific promise you can use success or failure only once | |
// p failure new IllegalArgumentException("Something went wrong") | |
// you can use these methods without the fear of an exception happening | |
// but if the promise is complete they have no effect the try... methods return true | |
// if the | |
println(p trySuccess "Sofoklis") | |
println(p tryFailure new IllegalArgumentException("Something went wrong")) | |
println("Promise loop start") | |
for (i ← 1 to 10000000) {} | |
println("Promise sample exit") | |
} | |
private def registerCallbacks(f: scala.concurrent.Future[String]): Unit = { | |
f onSuccess { | |
case s ⇒ println("success " + s) | |
} | |
f onComplete { | |
case s ⇒ println("complete " + s) | |
} | |
f onFailure { | |
case ex ⇒ println("failure " + ex.getMessage) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment