EzDevInfo.com

Future

Swift µframework providing Future<T, Error>

Disable future dates in jQuery UI Datepicker

Is it possible to disable future date from today?

Let say today is 23/10/2010, so 24/10/2010 onwards are disabled.

Sorry I am very new in jQuery and JavaScript.


Source: (StackOverflow)

How to cancel Future in Scala?

Java Future has cancel method, which can interrupt the thread, which runs the Future task. For example, if I wrap an interruptible blocking call in a Java Future I can interrupt it later.

Scala Future provides no cancel method. Suppose I wrap an interruptible blocking call in a Scala Future. How can I interrupt it?


Source: (StackOverflow)

Advertisements

Why using std::async from C++11?

I'm trying to explore all the options of the new C++11 standard in depth, while using std::async and reading its definition, I noticed 2 things, at least under linux with gcc 4.8.1 :

  • it's called async, but it got a really "sequential behaviour", basically in the row where you call the future associated with your async function foo, the program blocks until the execution of foo it's completed.
  • it depends on the exact same external library as others, and better, non-blocking solutions, which means pthread, if you want to use std::async you need pthread.

at this point it's natural for me asking why choosing std::async over even a simple set of functors ? It's a solution that doesn't even scale at all, the more future you call, the less responsive your program will be.

Am I missing something ? Can you show an example that is granted to be executed in an async, non blocking, way ?


Source: (StackOverflow)

Future[Option] in Scala for-comprehensions

I have two functions which return Futures. I'm trying to feed a modified result from first function into the other using a for-yield comprehension.

This approach works:

  val schoolFuture = for {
    ud <- userStore.getUserDetails(user.userId)
    sid = ud.right.toOption.flatMap(_.schoolId)
    s <- schoolStore.getSchool(sid.get) if sid.isDefined
  } yield s

However I'm not happy with having the "if" in there, it seems that I should be able to use a map instead.

But when I try with a map:

  val schoolFuture: Future[Option[School]] = for {
    ud <- userStore.getUserDetails(user.userId)
    sid = ud.right.toOption.flatMap(_.schoolId)
    s <- sid.map(schoolStore.getSchool(_))
  } yield s

I get a compile error:

[error]  found   : Option[scala.concurrent.Future[Option[School]]]
[error]  required: scala.concurrent.Future[Option[School]]
[error]         s <- sid.map(schoolStore.getSchool(_))

I've played around with a few variations, but haven't found anything attractive that works. Can anyone suggest a nicer comprehension and/or explain what's wrong with my 2nd example?

Here is a minimal but complete runnable example with Scala 2.10:

import concurrent.{Future, Promise}

case class User(userId: Int)
case class UserDetails(userId: Int, schoolId: Option[Int])
case class School(schoolId: Int, name: String)

trait Error

class UserStore {
  def getUserDetails(userId: Int): Future[Either[Error, UserDetails]] = Promise.successful(Right(UserDetails(1, Some(1)))).future
}

class SchoolStore {
  def getSchool(schoolId: Int): Future[Option[School]] = Promise.successful(Option(School(1, "Big School"))).future
}

object Demo {
  import concurrent.ExecutionContext.Implicits.global

  val userStore = new UserStore
  val schoolStore = new SchoolStore

  val user = User(1)

  val schoolFuture: Future[Option[School]] = for {
    ud <- userStore.getUserDetails(user.userId)
    sid = ud.right.toOption.flatMap(_.schoolId)
    s <- sid.map(schoolStore.getSchool(_))
  } yield s
}

Source: (StackOverflow)

Clojure mutable storage types

I'm attempting to learn Clojure from the API and documentation available on the site. I'm a bit unclear about mutable storage in Clojure and I want to make sure my understanding is correct. Please let me know if there are any ideas that I've gotten wrong.

Edit: I'm updating this as I receive comments on its correctness.


Disclaimer: All of this information is informal and potentially wrong. Do not use this post for gaining an understanding of how Clojure works.


Vars always contain a root binding and possibly a per-thread binding. They are comparable to regular variables in imperative languages and are not suited for sharing information between threads. (thanks Arthur Ulfeldt)

Refs are locations shared between threads that support atomic transactions that can change the state of any number of refs in a single transaction. Transactions are committed upon exiting sync expressions (dosync) and conflicts are resolved automatically with STM magic (rollbacks, queues, waits, etc.)

Agents are locations that enable information to be asynchronously shared between threads with minimal overhead by dispatching independent action functions to change the agent's state. Agents are returned immediately and are therefore non-blocking, although an agent's value isn't set until a dispatched function has completed.

Atoms are locations that can be synchronously shared between threads. They support safe manipulation between different threads.

Here's my friendly summary based on when to use these structures:

  • Vars are like regular old variables in imperative languages. (avoid when possible)
  • Atoms are like Vars but with thread-sharing safety that allows for immediate reading and safe setting. (thanks Martin)
  • An Agent is like an Atom but rather than blocking it spawns a new thread to calculate its value, only blocks if in the middle of changing a value, and can let other threads know that it's finished assigning.
  • Refs are shared locations that lock themselves in transactions. Instead of making the programmer decide what happens during race conditions for every piece of locked code, we just start up a transaction and let Clojure handle all the lock conditions between the refs in that transaction.

Also, a related concept is the function future. To me, it seems like a future object can be described as a synchronous Agent where the value can't be accessed at all until the calculation is completed. It can also be described as a non-blocking Atom. Are these accurate conceptions of future?


Source: (StackOverflow)

Get the status of a std::future

Is it possible to check if a std::future has finished or not? As far as I can tell the only way to do it would be to call wait_for with a zero duration and check if the status is ready or not, but is there a better way?


Source: (StackOverflow)

Waiting on a list of Future

I have a method which returns a List of futures

List<Future<O>> futures = getFutures();

Now I want to wait until either all futures are done processing successfully or any of the tasks whose output is returned by a future throws an exception. Even if one task throws an exception, there is no point in waiting for the other futures.

Simple approach would be to

wait() {

   For(Future f : futures) {
     try {
       f.get();
     } catch(Exception e) {
       //TODO catch specific exception
       // this future threw exception , means somone could not do its task
       return;
     }
   }
}

But the problem here is if, for example, the 4th future throws an exception, then I will wait unnecessarily for the first 3 futures to be available.

How to solve this? Will count down latch help in any way? I'm unable to use Future isDone because the java doc says

boolean isDone()
Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

Source: (StackOverflow)

Unable to use for comprehension to map over List within Future

I have this issue that I have to work around every time. I can't map over something that is contained within a Future using a for comprehension.

Example:

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

val f = Future( List("A", "B", "C") )
for {
  list <- f
  e <- list
} yield (e -> 1)

This gives me the error:

 error: type mismatch;
 found   : List[(String, Int)]
 required: scala.concurrent.Future[?]
              e <- list
                ^

But if I do this it works fine:

f.map( _.map( (_ -> 1) ) )

Should i not be able to do this by using a for comprehension, is the reason it works in my other example that I do not flatmap? I'm using Scala 2.10.0.


Source: (StackOverflow)

Wait for several Futures

Suppose I have several futures and need to wait until either any of them fails or all of them succeed.

For example: Let there are 3 futures: f1, f2, f3.

  • If f1 succeeds and f2 fails I do not wait for f3 (and return failure to the client).

  • If f2 fails while f1 and f3 are still running I do not wait for them (and return failure)

  • If f1 succeeds and then f2 succeeds I continue waiting for f3.

How would you implement it?


Source: (StackOverflow)

Scala: List[Future] to Future[List] disregarding failed futures

I'm looking for a way to convert an arbitrary length list of Futures to a Future of List. I'm using Playframework, so ultimately, what I really want is a Future[Result], but to make things simpler, let's just say Future[List[Int]] The normal way to do this would be to use Future.sequence(...) but there's a twist... The list I'm given usually has around 10-20 futures in it, and it's not uncommon for one of those futures to fail (they are making external web service requests). Instead of having to retry all of them in the event that one of them fails, I'd like to be able to get at the ones that succeeded and return those.

For example, doing the following doesn't work

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure

val listOfFutures = Future.successful(1) :: Future.failed(new Exception("Failure")) :: 
                    Future.successful(3) :: Nil

val futureOfList = Future.sequence(listOfFutures)

futureOfList onComplete {
  case Success(x) => println("Success!!! " + x)
  case Failure(ex) => println("Failed !!! " + ex)
}

scala> Failed !!! java.lang.Exception: Failure

Instead of getting the only the exception, I'd like to be able to pull the 1 and 3 out of there. I tried using Future.fold, but that apparently just calls Future.sequence behind the scenes.

Thanks in advance for the help!


Source: (StackOverflow)

Asynchronous IO in Scala with futures

Let's say I'm getting a (potentially big) list of images to download from some URLs. I'm using Scala, so what I would do is :

import scala.actors.Futures._

// Retrieve URLs from somewhere
val urls: List[String] = ...

// Download image (blocking operation)
val fimages: List[Future[...]] = urls.map (url => future { download url })

// Do something (display) when complete
fimages.foreach (_.foreach (display _))

I'm a bit new to Scala, so this still looks a little like magic to me :

  • Is this the right way to do it? Any alternatives if it is not?
  • If I have 100 images to download, will this create 100 threads at once, or will it use a thread pool?
  • Will the last instruction (display _) be executed on the main thread, and if not, how can I make sure it is?

Thanks for your advice!


Source: (StackOverflow)

Using C++11 futures: Nested calls of std::async crash: Compiler/Standard library bug?

After experiencing crashes when introducing nested calls of std::async in my real program, I was able to reproduce the problem in the following minimum example. It crashes often, but not always. Do you see anything what goes wrong, or is it a compiler or standard library bug? Note that the problem remains if get() calls to the futures are added.

#include <future>
#include <vector>

int main (int, char *[])
{
    std::vector<std::future<void>> v;
    v.reserve(100);
    for (int i = 0; i != 100; ++i)
    {
        v.emplace_back(std::async(std::launch::async, [] () {
            std::async(std::launch::async, [] { });
        }));
    }

    return 0;
}

I observe two different kinds of crashes: (in about every fifth run)

  • Termination with "This application has requested the Runtime to terminate it in an unusual way."
  • Termination after throwing an instance of 'std::future_error', what(): Promise already satisfied.

Environment:

  • Windows 7
  • gcc version 4.8.2 (i686-posix-dwarf-rev3, Built by MinGW-W64 project), as provided by Qt 5.3.2
  • Command line call: g++ -std=c++11 -pthread futures.cpp
  • Compiled and run on two independent machines

Option -pthread? Could it be that in my environment for some reason the option -pthread is silently not taken into account? I observe the same behavior with and without that option.


Source: (StackOverflow)

std::packaged_task not breaking promises on destruction?

I'm encountering something very weird when using packaged tasks. When reading ~packaged_task I get the impression that if a std::packaged_task is destroyed before it is executed, the promise will be broken and an attempt to get the result from the future should throw std::future_error.

However, on Visual Studio 2013 this doesn't seem to be the case. Take this following code:

#include <iostream>
#include <future>
#include <functional>

int main() {
    std::future<int> f;
    {
        std::packaged_task<int()> task([](){return 3; });
        f = task.get_future();
    }
    std::cout<<f.get()<<std::endl;
    return 0;
}

I'm expecting to get an std::future_error on f.get() but instead it blocks, waiting for the packaged task to be executed.

Trying another compiler: http://ideone.com/Wt0WOc does indeed throw a std::future_error("Broken promise")...

Am I seeing a bug in Visual Studio 2013 or have I missed something?


Source: (StackOverflow)

Map the Exception of a failed Future

What's the cleanest way to map the Exception of a failed Future in scala?

Say I have:

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global

val f = Future { 
  if(math.random < 0.5) 1 else throw new Exception("Oh no") 
}

If the Future succeeds with 1, I'd like to keep that, however if it fails I would like to change the Exception.

The best I could come up with is transform, however that requires me to make a needless function for the success case:

val f2 = f.transform(s => s, cause => new Exception("Something went wrong", cause))

Is there any reason there is no mapFailure(PartialFunction[Throwable,Throwable])?


Source: (StackOverflow)

Get rid of Scala Future nesting

Again and again I am struggling when a function relies on some future results. This usually boils down to a result like Future[Seq[Future[MyObject]]]

To get rid of that I now use Await inside a helper function to get a non-future object out and reduce the nesting.

It looks like this

def findAll(page: Int, perPage: Int): Future[Seq[Idea]] = {
    val ideas: Future[Seq[Idea]] = collection.find(Json.obj())
    // [...]

    ideas.map(_.map { // UGLY?
      idea => {
        // THIS RETURNED A Future[JsObject] before
        val shortInfo: JsObject = UserDao.getShortInfo(idea.user_id)
        idea.copy(user_data = Some(shortInfo))
      }
    })
}

This code works but to me it looks quite hacky. The two map calls are another flaw. I spent hours trying to figure out how to keep this completely asynchronous and returning a simple future Seq. How can this be solved using Play2 best practices?

Edit To make the usecase more clear:

I have an object A from mongodb (reactivemongo) and want to add information coming from another call to mongodb getShortInfo. It's a classical "get user for this post" case that would be solved with a join in RDBMS. getShortInfo naturally would produce a Future because of the call to the db. To reduce the nesting within findAll I used Await(). Is this a good idea?

findAll is called from an asynchronous Play action, converted into Json and sent over the wire.

def getIdeas(page: Int, perPage: Int) = Action.async {

  for {
    count <- IdeaDao.count
    ideas <- IdeaDao.findAll(page, perPage)
  } yield {
    Ok(Json.toJson(ideas))
  }
}    

So I think returning a Seq[Future[X]] from findAll won't bring better performance as I have to wait for the result anyways. Is this correct?

The usecase in short: Take a Future call returning a Sequence, use each element of the result to create another Future call, return the result to an asynchronous action in a way that no blocking situations should occur.


Source: (StackOverflow)