Skip to content

Instantly share code, notes, and snippets.

@aaronlifton3
Forked from ekmett/Speculation.scala
Last active August 29, 2015 14:07
Show Gist options
  • Save aaronlifton3/5cac688c91c302e78d30 to your computer and use it in GitHub Desktop.
Save aaronlifton3/5cac688c91c302e78d30 to your computer and use it in GitHub Desktop.
package speculation
import java.util.concurrent.{ Callable, ExecutorService, Future }
class Speculation(val executor: ExecutorService, val mayInterruptIfRunning: Boolean) {
def spec[A,B](guess: => A)(f: A => B)(actual: => A): B = {
val g = executor.submit(new Callable[A] {
def call = guess
})
val speculation = executor.submit(new Callable[B] {
def call = f(g.get())
})
val a = actual
val guessed = g.get()
if (a == guessed) {
speculation.get()
} else {
speculation.cancel(mayInterruptIfRunning)
f(actual)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment