FAQ Database Discussion Community


How to page REST calls in a future with Dispatch and Scala

scala,rest,future
I use Scala and Dispatch to get JSON from a paged REST API. The reason I use futures with Dispatch here is because I want to execute the calls to fetchIssuesByFile in parallel, because that function could result in many REST calls for every lookupId (1x findComponentKeyByRest, n x fetchIssuePage,...

How to manipulate the result of a Future in javafx

java,model-view-controller,javafx,javafx-8,future
This is my JavaFX Controller public class MainController { private Future<Graph> operation; private ExecutorService executor = Executors.newSingleThreadExecutor(); @FXML private void createSession() { //invoked by a button click in the view //GraphCreationSession implements Callable<Graph> GraphCreationSession graphSession = new GraphCreationSession(); if (operation != null && !operation.isDone()) { //cancel previous session operation.cancel(true); }...

stuck with futures in scala

scala,future
Basically I'm running two futures queries on cassandra, then I need to do some computation and return the value(an average of values). Here is my code: object TestWrapFuture { def main(args: Array[String]) { val category = 5392 ExtensiveComputation.average(category).onComplete { case Success(s) => println(s) case Failure(f) => throw new Exception(f) }...

Using futures and Thread.sleep

scala,future
By executing this scala code, I don't have any output in the console. (I don't really understand what is happening) If I remove Console.println("Console.println OK!") => everything seems fine. If I remove Thread.sleep(2000) => everything seems fine. Do you have any ideas about this ? Thank you very much! Clément...

When can a Future return an Exception that is not thrown from within the Future's body?

scala,concurrency,future
The more general question here is: in production-quality code, does one need to be concerned with exceptions produced by the ExecutionContext or other concurrency infrastructure, outside of the execution of the future's body? For example, if some failure happens with the thread pool, will I see an exception returned in...

Where is future necessary to run a sequence of async functions in node?

javascript,node.js,meteor,future
Previously, I have used future.wait() to wait for a value before I return it to the next function. (I am coding in Meteor by the way) After reading node's non-blocking I/O architecture, doesn't my following method (which does work) defeat the purpose entirely? What I am doing is passing the...

Tornado and concurrent.futures.Executor

asynchronous,tornado,future
I'm learning about async and Torando and struggling. First off is it possible to use executor class in Tornado? The below example i'm creating a websocket and when receiving a message I want to run check() as another process in the background. This is a contrived example just for my...

Why does the andThen of Future not chain the result?

scala,future
The andThen meaning I learned from this answer is a function composer. Say that f andThen g andThen h will equal to h(g(f(x))) This implies the h function will receive input from g(f(x)) But for the andThen in Future, all the closure of the following andThen always receives the result...

Scala: Ignore Future return value, but chain them

scala,future,for-comprehension
How should I write code, when I do not care about the returned value. Example: for { a <- getA // I do not care about a, but I need to wait for the future to finish b <- getB } yield (b) ...

Dependent futures

scala,playframework-2.0,future
Starting playing with Scala futures, I get stuck with dependent futures. Let's get a example. I search for places and get a Future[Seq[Place]]. For each of theses places, I search for the closest subway stations (the service resurns a Future[List[Station]]). I would write this: Place.get() .map { places => places.map...

How to compose Observables to avoid the given nested and dependent callbacks?

java,future,rx-java
In this blog, he gives this (copy/pasted the following code) example for the callback hell. However, there is no mention of how the issue can be eliminated by using Reactive Extensions. So here F3 depends upon F1 completion and F4 and F5 depend upon F2 completion. Wondering what would be...

InterruptedException not catch?

java,interrupt,future
I'm trying to implement the Raft Consensus Algorithm for a Distributed System Project, in particular now I'm concentrating about Leader Election Algorithm. Essentially, there are 3 states: Follower Candidate Leader The state passage is pretty complicate if you don't know the algorithm, and I think that the only useful things...

What does Future() means in NHibernate?

c#,nhibernate,future
I'm new to NHibernate the description for IEnumerable Future(); says the following // Summary: // Get a enumerable that when enumerated will execute a batch of queries in // a single database roundtrip Just wondering what does it means, the description has nothing to do with the word 'future'...

AddItem in CMFCToolBarComboBoxButton - new value is not shown

c++,visual-studio-2008,mfc,future,pack
I am using Visual Studio 2008. I have a problem with AddItem in CMFCToolBarComboBoxButton. I added CMFCToolBarComboBoxButton to tool bar (I used this solutions: click here). The problem is call AddItem() method in run time. I checked in Quick Watch object which calls this method. In this object, the new...

nvcc/CUDA 6.5 & c++11(future) - gcc 4.4.7

c++11,gcc,cuda,future
When I compile the following code containing the design C++11, I get errors - it does not compile. I've tried with different flags, but I haven't found a solution. My setting: CUDA 6.5, gcc 4.4.7 I am not able to change the settings. How can I still make this work?...

Scala future return based on first future result

scala,filter,akka,future,for-comprehension
I have a Scala future that calls an api and returns future, if the result isn't correct, then another api call will be submitted with first future's result and returned as future. This is what I have so far. val fut1 = Future(queryFirst) val fut2 = fut1 map { case...

All Scala futures completed

scala,future
I have an akka actor in which I have several futures in scala that do just some extra work and save the computation into the shared variable. After the main work is done, I want to wait for these 'extra' futures and reply with an answer. The simple code is...

Scala: How to combine methods that return a Future

scala,future
Given a Map that stores exchange rates from EUR/USD to BTC... val btcRates = Map("EUR" -> 0.0036, "USD" -> 0.0045) ... and the following two methods... // returns a Future containing a Map of value to convert to BTC def getAmounts = Future(Map("EUR" -> 500.0, "USD" -> 550.0, "CHF" ->...

implementing PriorityQueue on ThreadPoolExecutor

java,priority-queue,future,threadpoolexecutor
Been struggling with this for over 2 days now. implemented the answer I saw on here Specify task order execution in Java public class PriorityExecutor extends ThreadPoolExecutor { public PriorityExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } //Utitlity method to create...

error C2248: 'std::promise<_Ty>::promise' : cannot access private member declared in class 'std::promise<_Ty>'

c++,multithreading,c++11,promise,future
How can I correct the code below in order to avoid the error message? Is this code not supposed to work? Is there a different technique (packaged_task, asynch) that can be used? #include <list> #include <future> using namespace std; template<typename T> struct sorter { struct chunk_to_sort { std::list<T> data_m; std::promise<std::list<T>...

Future Object serialized on complex object

java,object,serialization,future,complextype
I want to have a Future object returned from a thread pool, which has complex attributes. Should I use the serializable interface for this case?

Scala: How to count how many times a Future pair succeded

scala,future
In the following code snippet invokes getAmounts to get some amounts grouped by currency and then invokes getRates to apply the corresponding exchange rate: def getAmounts = Future(Map("EUR" -> 500d, "USD" -> 400d)) def getRates = Future(Map("EUR" -> 1d, "USD" -> 0.9)) getAmounts.flatMap { amounts => getRates.map { rates =>...

Awaiting all Scala Futures to complete

scala,future,scrimage
I have a for comprehension like this using an image library that supports concurrent operations https://github.com/sksamuel/scrimage : for ( file <- myDirectory.listFiles; image <- AsyncImage(file); scaled <- image.scale(0.5) // possibly more ops here? ) { scaled.writer(Format.PNG).write(new File(dirOutput + file.getName)) } here is the definition for write(): def write(out: OutputStream)(implicit executionContext:...

First Object in Set> that satisfies a predicate

java,functional-programming,java-8,future,rx-java
Abstract idea I want to get the first value coming out of a set of Futures, that satisfies a given predicate. If a satisfying value is found, all other Futures should be cancelled. If no value is found after all Futures have returned the execution should be terminated (by returning...

Scala - Futures and Eithers

scala,dictionary,future,either
this thread gave me an idea how to structure my code: Scala-way to handle conditions in for-comprehensions? The part in question: // First create the JSON val resultFuture: Future[Either[Failure, JsResult]] = for { userRes <- userDao.findUser(userId) user <- userRes.withFailure(UserNotFound).right authRes <- userDao.authenticate(user) auth <- authRes.withFailure(NotAuthenticated).right goodRes <- goodDao.findGood(goodId) good <-...

Loading complex graph in nhibernate

c#,nhibernate,future
Imagina i have pretty complex model graph such as for an example: Orchestra -> Musicians -> Instruments -> Properties -> Items -> Songs -> Parts I know in theory how Futures works but how do i load this complete graph lets say for a concrete musician (specified by id). I...

Future cancel method documentation

java,concurrency,documentation,future,java.util.concurrent
According to http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html isDone returns true if cancel(boolean mayInterruptIfRunning) was called. After this method returns, subsequent calls to isDone() will always return true. However, it is possible that task is running and mayInterruptIfRunning is set to false. So, what should return isDone() right after that call? true because of cancel...

How to implement immutable cache in Scala?

scala,caching,concurrency,future
Suppose I have a server, which calls a time consuming function slow: Int => String upon a client request. If slow does not return within the timeout the server returns an error to the client. def trySlow(timeout: Duration)(id: Int): Try[String] = { val fut = Future(slow(id)) try { Await.ready(fut, timeout).value...

Is it possible to pass Function to ExecutorService instead of callable in Java 8?

java-8,future,executorservice,callable
public class myService { @Autowired ExecutorService executor; public Result getServiceResult(Token token, Profile profile){ //validate token and profile return getResult(token, profile).get(); } private getResult (Token token, Profile profile){ Future<Result> = threadPoolExecutor.submit( () -> myManager.createAccount(token, profile)); } } This code runs fine at my current work. I am not able to able...

Sum of integer values of a Future

dart,future,dart-async
I'm trying to parse a HTML document, get all the image-sources and then add the size of all pictures together. Parsing the document works fine, so does getting the image-sources and getting their size. main(){ print("Please input an URL"); var url = stdin.readLineSync(); getImageUrls(url).then((list) { list.forEach((imageUrl) { getImageSize(imageUrl).then((r) { print("$imageUrl,...

convert Scala Future to Twitter Future

scala,future,finagle
I use Finagle as a web server which I want to return Scala-Futures from my application logic. How to convert scala.concurrent.Future to com.twitter.util.Future, in a non-blocking way of course?

Non blocking way of adding a work item to array or list

c++,c++11,threadpool,future,lock-free
Edit: I now have finished my queue (overcoming the problem described below, and more). For those interested it can be found here. I'd be happy to hear any remarks:). Please note the queue isn't just a work item queue, but rather a template container which of course could be instantiated...

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

c++,exception,c++11,asynchronous,future
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;...

Ruby on Rails Display the future date from the database that is closest to today's

ruby-on-rails,ruby,date,time,future
In my Ruby on Rails application I am building a cinema system. On index.html.erb what I want to do is make it so that if the film is not yet released it shows the release date (that works) but if it has already been released and there are showings for...

Best Practice for Returning Java Future from Library

java,future
I am working on a Java library that implements the Jump Point Search algorithm. There are two exposed methods you can call to run the search. A synchronous one and one that returns a Java Future of the results. public Future<Queue<T>> findPath(T start, T goal) { FutureTask<Queue<T>> future = new...

cancel() vs remove() on executors

java,future,threadpoolexecutor
Recently I worked with ThreadPoolExecutor and priorityqueue and came across both methods future.cancel() on a future task. And task.remove() on the task it self, to remove it from the queue. What is the better option? is there any difference? I can save list of both (the future object received from...

Specs2 Data Tables with future results

scala,integration-testing,future,specs2
I'm struggling with following problem: I have a method that returns a Future[Result] where Result is the thing I would like to check with a data table row in specs2. As I understand the following code would block each time and wait for the result to be available. def getDataForInput(input:...

clojure future vs delay

clojure,delay,future,core
I have been reading through Programming in Clojure and found thing text (defn get-document [id] ; ... do some work to retrieve the identified document's metadata ... {:url "http://www.mozilla.org/about/manifesto.en.html" :title "The Mozilla Manifesto" :mime "text/html" :content (delay (slurp "http://www.mozilla.org/about/manifesto.en.html"))}) if callers are likely to always require that data, the change...

Exception with ScalaZ OptionT

scala,future,scalaz
Consider the following code which uses ScalaZ's OptionT: val answer = for { customer <- optionT(function1(codeString)) customerId <- someOptionT(Future(Seq(function2(customer))) alerts <- someOptionT(Future.sequence(function3(customerId)) } yield alerts function1 returns Future[Option[Customer]] function2 returns String function3 returns Seq[Future[Option[String]]] Meanwhile this is someOptionT def someOptionT[T](t: Future[T]): OptionT[Future, T] = optionT[Future](t.map(Some.apply)) I get the following exception...

Scala Futures callback hell

scala,callback,future
I've been reading many times about Scala Futures reducing callback problems. I've got a code that started to look problematic. val a = Future(Option(Future(Option(10)))) a.map { b => b.map { c => c.map { d => d.map { res => res + 10 } } } } How can I...

Wait for a list of futures with composing Option in Scala

scala,future
I have to get a list of issues for each file of a given list from a REST API with Scala. I want to do the requests in parallel, and use the Dispatch library for this. My method is called from a Java framework and I have to wait at...

Scala: Warn if block of code is executing for more than certain duration?

scala,akka,future
I wan to do something like this: def warnEvery[A](duration: Duration)(block: => A): A = { val start = DateTime.now val f = Future(f) while(!f.isComplete) { Thread.sleep(duration) if (!f.isComplete) { // Trigger a stack trace warning message Log.warn(s"Block is running for ${DateTime.now() - start}", new Throwable()) } } f.result } The...

Multiple Futures in a Sequence in Scala

scala,future
I have two computations that happen in a Future as below: val comp1 = Future { ... } val comp2 = Future { ... } I want this to run such that comp2 always runs after comp1 has completed! I know that using a for expression, I can compose these...

How to recover an error from a Future in an EssentialAction

scala,playframework,future,iteratee
Starting with the example from this post, I'm wondering how to deal with recover: def HasToken(action: String => EssentialAction): EssentialAction = EssentialAction { requestHeader => val maybeToken = requestHeader.headers.get("session") val futureIteratee: Future[Iteratee[Array[Byte], SimpleResult]] = maybeToken map { token => //This returns a future... Session.find(token).map { case Some(session) => action(session)(requestHeader) case...

Android volley Timeout Exception when using RequestFuture.get()

java,android,network-programming,android-volley,future
In my Fragment, i am trying to use TMDB's open movie DB to get details about "Now Playing" Movies. If i use RequestFuture.get(time, TimeUnit) method to execute this volley request i always get a timeout error. If i manually test the same Url in Safari, i get the results instantaneously....

Is there a build in “slow” Future.traverse version?

scala,future
I discovered that building a lot of Futures for one user request generally is a bad practice. These Futures can fill an execution context which will affect other requests. This is unlikely something you really want. Keeping Futures number small is quite simple - create new Futures only in for-comprehensions,...

Java Future.isDone returning true, even though it shouldn't, which halts program progress

java,future,executorservice
I have a SwingWorker which initiates a LinkedBlockingQueue, passes it to another method (PortalDriver, below), then reads from it in the doInBackground() method. The LinkedBlockingQueue holds futures for a custom object (and it is definitely filled correctly). As a check, the objects that I am creating (via an ExecutorService), have...

How to fail promise in Scala

scala,promise,future
In Scala documentation, there is an example how to pick future which succeeds faster by using promises. http://docs.scala-lang.org/overviews/core/futures.html#promises def first[T](f: Future[T], g: Future[T]): Future[T] = { val p = promise[T] f onSuccess { case x => p.trySuccess(x) } g onSuccess { case x => p.trySuccess(x) } p.future } This function...

CompletableFuture return totally different future

java-8,future
I am researching about Java 8 CompletableFuture (Promise in languages like Scala or JS). May be I've done something wrong or didn't not found any description of this. Future that returned after setup few callbacks on it return completely independent future. I have some unit test for that: public class...

Specs2 with Futures and Case Classes

scala,future,specs2
I have a lot of problems working with futures as an answer of using Scala Dispatch for asynchronous HTTP calls. I also used Case Class Matchers lets suppose that I make a call here: http://ip.jsontest.com/ wich returns this json: { "ip": "x.xxx.xxx.xxx" } so I build my Specification as this...

Consuming a service using WS in Play

scala,future,playframework-2.3
I was hoping someone can briefly go over the various ways of consuming a service (this one just returns a string, normally it would be JSON but I just want to understand the concepts here). My service: def ping = Action { Ok("pong") } Now in my Play (2.3.x) application,...

In Scala, why is there no implementation for `Future.onComplete`?

scala,concurrency,akka,future
In the source code of Future module, I saw the definition of onComplete like this: /** When this future is completed, either through an exception, or a value, * apply the provided function. * * If the future has already been completed, * this will either be applied immediately or...

Bulkheading strategies for Akka actors

java,asynchronous,akka,blocking,future
I have a scenario where an important actor needs to make a call to a slow (15 - 20 seconds) remote system: // Non-actor code equivalent public Result makeSlowNetworkCall(Request request) { Result result = slowServiceClient.soooooSlow(request); // Could be up to 15 - 20 SECONDS (mehhhh) return result; } The Akka...

Multiprocessing and a global manager

python,dictionary,process,multiprocessing,future
I have import concurrent.futures from multiprocessing import Process,Manager,freeze_support from functools import partial def setup(): freeze_support() global manager manager=Manager() global dict1 dict1=manager.dict() global dict2 dict2=manager.dict() load_stuff() and later: def foo(file): #do some stuff foobar() def foobar(): #look up some stuff in dict1,dict2 def load_stuff(): f=partial(foo,dict1,dict2) with concurrent.futures.ProcessPoolExecutor() as executor: for users,...

How to use the Akka ask pattern without blocking

scala,asynchronous,akka,future
Hi I have a actor which is responsible for fetching data from a database, turning it into a list and sending it back to the sender. I am using the ask pattern to receive response from my actor, because I don't want to use await.result because this approach will block...

Convert scala future to java future

java,scala,akka,future
I have a generated java interface containing a method: public Future<?> getCustomersAsync(AsyncHandler<Customer> asyncHandler); I want to implement it using Akka. I wrote following: override def getCustomerAsync(asyncHandler: AsyncHandler[Customer]): Future[_] = { myActorRef.ask(GetCustomer, system.actorOf(Props[Responder])) } The issue is that ask returns scala.concurrent.Future[Any] and the method must return java.util.concurrent.Future[?]. Error:(33, 17) type mismatch;...

Is there a way to get a Callable back from a FutureTask?

java,future,callable
If I have a FutureTask<String> f, can I get the Callable<String> c object that was used in his constructor? Something like: Callable<String> c = f.getCallable(); ...

Clear onComplete functions list in Promise

scala,promise,future
This snippet val some = Promise[Int]() some.success(20) val someFuture = some.future someFuture.onSuccess {case i => println(i)} someFuture.onComplete {case iTry => List(println(iTry.get*2), println(iTry.get*3))} creates promise with list of 3 callbacks(List[CallbackRunnable]) on complete. Is there a way to clear this List or rewrite it?...

Where should I put completer.complete() in this series of Future functions?

dart,future,dart-async
My function have to create a directory, and copy the entire folder hierarchy from another directory to this new one. All of the operation are done asynchronously, but I want this function to return a Future that when I call the .then(result) on it, will have done all of the...

How to implement Future as Applicative in Scala?

scala,concurrency,functional-programming,future,applicative
Suppose I need to run two concurrent computations, wait for both of them, and then combine their results. More specifically, I need to run f1: X1 => Y1 and f2: X2 => Y2 concurrently and then call f: (Y1, Y2) => Y to finally get a value of Y. I...

Akka Future Respose to a Sender

scala,akka,future
I came across the following SIP: http://docs.scala-lang.org/sips/pending/spores.html As I was reading through, I came across this example: def receive = { case Request(data) => future { val result = transform(data) sender ! Response(result) } } There was a description below in that article: > Capturing sender in the above example...

In Scala, how to do type conversion for Future[Option[A]]?

scala,generics,functional-programming,future
For example, there are two classes: A and B. And there is a method in A called toB. Now there is a value a which is of type Future[Option[A]], what will be the most elegant way to convert it to Future[Option[B]]? Currently I'm using a.map(_.map(_.toB)), but I think it looks...

Do associated futures complete on closing of channel?

java,asynchronous,network-programming,netty,future
If I create a future by Channels.future(Channel), is it automatically completed (to failure?) when the channel is closed? (Netty 3.10.0)

Returning multiple values from a function with std::future

multithreading,c++11,future
According to this Q&A, std::future works if a function returns a value, but you can't pass references and get multiple values. So a function like this will give no results with std::future: void doSomething(int &a, int &b) { a = 1; b = 2; } My idea was to create...

Understanding Scala Futures and Promises

scala,promise,future
I'm trying to get my head around this concept. I clearly understand what Futures are. I'm little bit bemused with Promises. The code snippet below: val p = Promise[Int]() // gives me a DefaultPromise val f = p.future // gives me the future computation for the Promise p Now what...

Why does my simple scala object hangs for a minute or so while it includes a future

scala,concurrency,future
I am learning scala futures and I hit my question already. I have a very simple example import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent._ import scala.util.{Failure, Success} /** * Created by dummy on 05/02/15. */ object FutureUtils extends App{ val f = Future { Thread.sleep(1000) println("I am learning scala futures") "learning" } f...

Akka Gotchas when dealing with Futures

akka,future
Consider the following code bit: def receive = { case ComputeResult(itemId: Long) => //val originalSender = sender computeResult(itemId).map { result => originalSender ! result } } The computeResult results in a Future, so how would the introduction of a val prevent my from sending the result to the wrong sender?...