Skip to content

Instantly share code, notes, and snippets.

@pnf
Created May 16, 2024 14:53
Show Gist options
  • Save pnf/eb3851dec159cc5c918383380922d091 to your computer and use it in GitHub Desktop.
Save pnf/eb3851dec159cc5c918383380922d091 to your computer and use it in GitHub Desktop.
import java.util.concurrent.ConcurrentLinkedQueue
import scala.annotation.tailrec
import scala.concurrent.{ExecutionContext, Future, Promise}
implicit val ec = ExecutionContext.global
val data = Map(
"getBff 1" -> 3,
"getBff 2" -> 4,
"getFN 1" -> "Harry",
"getFN 2" -> "Biff",
"getLN 3" -> "Jones",
"getLN 4" -> "Smith")
case class Query[A](s: String) {
private val p = Promise[A]()
def future = p.future
def fulfill(): Unit = p.success(data(s).asInstanceOf[A])
}
val queries = new ConcurrentLinkedQueue[Query[_]]
def query[A](cmd: String): Future[A] = {
val q = Query(cmd)
queries.add(q)
q.future
}
import scala.annotation.tailrec
@tailrec
def runBatch(): Unit = {
val q = queries.poll()
if (q ne null) {
q.fulfill()
runBatch()
}
}
def getBff(i: Int) = query[Int](s"getBff $i")
def getFirstName(i: Int) = query[String](s"getFN $i")
def getLastName(i: Int): Future[String] = query[String](s"getLN $i")
def par[A,B](f1: Future[A], f2: Future[B]): Future[(A,B)] = for(a<-f1;b<-f2) yield(a,b)
val x = Future.traverse(Seq(1,2))(i =>
for {
bff <- getBff(i)
fn <- getFirstName(i)
// (bff, fn) <- par(getBff(i), getFirstName(i))
ln <- getLastName(bff)
} yield s"$fn $ln")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment