Skip to content

Instantly share code, notes, and snippets.

@jorgeortiz85
Last active July 8, 2016 21:43
Show Gist options
  • Save jorgeortiz85/5288387 to your computer and use it in GitHub Desktop.
Save jorgeortiz85/5288387 to your computer and use it in GitHub Desktop.
import com.twitter.util.{Duration, Future, FuturePool, Try}
import java.util.concurrent.{LinkedBlockingQueue, ThreadPoolExecutor, TimeUnit}
val poolSize = 4
val queue = new LinkedBlockingQueue[Runnable]()
val executor = new ThreadPoolExecutor(poolSize, poolSize, 0L, TimeUnit.MILLISECONDS, queue)
val futurePool = FuturePool(executor)
def doWork(n: Int): Int = {
Thread.sleep(1000)
n
}
def niceThread(n: Int): Future[Int] = (futurePool {
doWork(n)
futurePool {
doWork(n)
}
}).flatten
val data1F = niceThread(1)
val data2F = niceThread(2)
val data3F = niceThread(3)
val data4F = niceThread(4)
val resultF =
for {
data1 <- data1F
data2 <- data2F
data3 <- data3F
data4 <- data4F
} yield {
data1 + data2 + data3 + data4
}
resultF.get(Duration.fromSeconds(3))
@dayorbyte
Copy link

Is the key to this working that the outer future pool call is returning a future, and so flatten returns the inner future?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment