future

How does std::async “store” an arbitrary exception?

折月煮酒 提交于 2019-12-10 18:04:59
问题 I am not able to understand how is it possible for std::async to store any exception, not just something derived from std::exception . I played around with the code below #include <iostream> #include <future> #include <chrono> void f() { std::cout << "\t\tIn f() we throw an exception" << std::endl; throw 1; // throw an int } int main() { std::future<void> fut = std::async(std::launch::async, f); std::cout << "Main thread sleeping 1s..." << std::endl; std::this_thread::sleep_for(std::chrono:

Why do we need both Future and Promise?

主宰稳场 提交于 2019-12-10 16:39:15
问题 As I know, Future is read-only and Promise is write-once data structure. We need a Promise to complete a Future For example, object Lie extends Throwable val lie = Future { throw Lie } val guess = Promise[String]() lie.onComplete { case Success(s) => guess.success("I knew it was true!") case Failure(t) => guess.failure("I knew it was lie")} // return type: Unit guess.future.map(println) // res12: scala.concurrent.Future[Unit] = List() // I knew it was lie! // Requires Promise to chain Future

ScalaTest can't verify mock function invocations inside Future

[亡魂溺海] 提交于 2019-12-10 16:38:17
问题 I'm trying to use Scala's Future together with ScalaTest and Mockito, but with a very simple test case, I'm not able to verify any of the invocations on a mocked function inside the Future. import org.mockito.Mockito.{timeout, verify} import org.scalatest.FunSpec import org.scalatest.mockito.MockitoSugar import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class FutureTest extends FunSpec with MockitoSugar { it("future test") { val mockFunction = mock[() =>

How to transform failed future exceptions in Scala?

时间秒杀一切 提交于 2019-12-10 15:49:10
问题 I have always used recover to transform exceptions in failed futures similar to def selectFromDatabase(id: Long): Future[Entity] = ??? val entity = selectFromDatabase(id) recover { case e: DatabaseException => logger.error("Failed ...", e) throw new BusinessException("Failed ...", e) } This code snippet transforms a DatabaseException into a BusinessException . However, from a comment in the question: Scala recover or recoverWith ... generally speaking the point of "recover" and "recoverWith"

traversing a List<Future> object throws IndexOutOfBounds exception

一个人想着一个人 提交于 2019-12-10 15:41:57
问题 I have an ExecutorService which is used to invoke a Collection of Callable obejcts and returns a List of Future objects corresponding to Callable elements in the collection. However, somewhere while traversing the list, it throws the following exception : java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: 7, Size: 1 at java.util.concurrent.FutureTask.report(Unknown Source) at java.util.concurrent.FutureTask.get(Unknown Source) at com.soc.transformcsv

Where to put dispatch.Http.shutdown()

落花浮王杯 提交于 2019-12-10 14:56:31
问题 where to place the call to dispatch.Http.shutdown() if there are n independent Http calls like, for example: import com.typesafe.scalalogging.slf4j.Logging import org.json4s._ import org.json4s.native.JsonMethods._ import scala.util.{ Failure, Success } object Main extends App with Logging { logger.debug("github.cli") // GET /users/defunkt: `curl https://api.github.com/users/defunkt` val host: dispatch.Req = dispatch.host("api.github.com").secure val request: dispatch.Req = host / "users" /

How do I gracefully shutdown the Tokio runtime in response to a SIGTERM?

青春壹個敷衍的年華 提交于 2019-12-10 14:40:06
问题 I have a main function, where I create a Tokio runtime and run two futures on it. use tokio; fn main() { let mut runtime = tokio::runtime::Runtime::new().unwrap(); runtime.spawn(MyMegaFutureNumberOne {}); runtime.spawn(MyMegaFutureNumberTwo {}); // Some code to 'join' them after receiving an OS signal } How do I receive a SIGTERM , wait for all unfinished tasks ( NotReady s) and exit the application? 回答1: Dealing with signals is tricky and it would be too broad to explain how to handle all

How can I flatten this Future[T] structure?

我的未来我决定 提交于 2019-12-10 12:34:46
问题 Given the following example: val handler : Connection = new DatabaseConnectionHandler() val result : Future[Future[Future[Option[ResultSet]]]] = handler.connect .map( (parameters) => handler ) .map( connection => connection.sendQuery("BEGIN TRANSACTION SERIALIZABLE") ) .map( future => future.map( query => query.rows ) ) .map( future => handler.sendQuery("COMMIT").map( query => future ) ) Is it possible to flatten it to receive a Future[Option[ResultSet]] at the end instead of this future

scala Future processing depth-first not breadth-first

南楼画角 提交于 2019-12-10 12:05:13
问题 I have a large computation roughly based on the following pattern : def f1(i:Int):Int = ??? def f2(i:Int):Int = ??? def processA(l: List[Int]) = l.map(i => Future(f1(i))) def processB(l: List[Int]) = { val p = processA(l) p.map(fut => fut.map(f2)) } def main() = { val items = List( /* 1k to 10k items here */ ) val results = processB(items) results.map(_.onComplete ( ... )) } The problem I encounter, if my understanding is correct, is that the processing is breadth-first. ProcessA starts

Scala Synchronising Asynchronous calls with Future

烈酒焚心 提交于 2019-12-10 11:45:31
问题 I have a method that does a couple of database look up and performs some logic. The MyType object that I return from the method is as follows: case class MyResultType(typeId: Long, type1: Seq[Type1], type2: Seq[Type2]) The method definition is like this: def myMethod(typeId: Long, timeInterval: Interval) = async { // 1. check if I can find an entity in the database for typeId val myTypeOption = await(db.run(findMyTypeById(typeId))) // I'm getting the headOption on this result if (myTypeOption