Skip to content

Instantly share code, notes, and snippets.

@kevinlynx
Created May 8, 2014 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinlynx/7764ed9ccfe083677a7e to your computer and use it in GitHub Desktop.
Save kevinlynx/7764ed9ccfe083677a7e to your computer and use it in GitHub Desktop.
package lichecker
import scala.concurrent._
import scala.concurrent.duration.Duration
import ExecutionContext.Implicits.global
import com.codemacro.AsyncTask
object FutureList {
def run[T, T2](args: List[T], fn: => T => T2, max: Int): List[T2] = {
val groups = args.grouped(max).toList
groups.flatMap(as => run(as, fn))
}
def run[T, T2](args: List[T], fn: => T => T2): List[T2] = {
val futures = args.map(a => actorWorker(a, fn))
val retsTmp = Future.sequence(futures)
Await.result(retsTmp, Duration.Inf)
}
private def actorWorker[T, T2](arg: T, fn: => T => T2) = {
val p = promise[T2]
def adapter(): Unit = {
val ret = fn(arg)
p.success(ret)
}
AsyncTask.run(adapter)
p.future
}
def main(args: Array[String]): Unit = {
def fn(t: Int) = {
Thread.sleep(t)
println(t)
t + 1
}
val rets = run(List(1000, 2000, 3000, 4000, 5000), fn, 5)
rets.foreach(println(_))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment