Created
May 8, 2014 13:25
-
-
Save kevinlynx/7764ed9ccfe083677a7e to your computer and use it in GitHub Desktop.
This file contains 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 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