Skip to content

Instantly share code, notes, and snippets.

@joshlemer
Created March 13, 2017 17:00
Show Gist options
  • Save joshlemer/a07c708f6e29b59c68ad4789d68dad94 to your computer and use it in GitHub Desktop.
Save joshlemer/a07c708f6e29b59c68ad4789d68dad94 to your computer and use it in GitHub Desktop.
object OtherMain extends App {
import scala.concurrent.{ExecutionContext, Future}
import java.util.concurrent.{ArrayBlockingQueue, Executors, ThreadPoolExecutor, TimeUnit}
val numWorkers = 2
val queueCapacity = 10
val q =
new ArrayBlockingQueue[Runnable](queueCapacity) {
override def offer(e: Runnable) = {
println("offering, size = " + size)
put(e); // may block if waiting for empty room
true
}
}
implicit val ec = ExecutionContext.fromExecutorService(
new ThreadPoolExecutor(
numWorkers, numWorkers,
0L, TimeUnit.SECONDS,
q
)
)
trait MainAndCallbackExecutionContext {
def execute(runnable: Runnable): Unit
def executeCallback(runnable: Runnable): Unit
}
implicit class FutureOps[T](future: Future[T]) {
def map[B](f: T => B)(implicit ec: MainAndCallbackExecutionContext): Future[B] = ??? //ec.executeCallback(???)
}
(0 until 20).map{ i =>
println("submitting " + i)
val first = Future{
println("starting " + i)
// Thread.sleep(Random.nextInt(10000))
Thread.sleep(10000)
println("finishing " + i)
i
}
println("starting map " + i + " queue size is " + q.size)
val mapped = first.map{ i =>
println("mapping " + i)
}(scala.concurrent.ExecutionContext.Implicits.global)
println("submitted map " + i + " queue size is " + q.size)
mapped
}
println("finished!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment