I have a Scala Play application and one of the controllers fires a Future which does some logging. I have a simple call back function which executes when the Future completes.
I have written a test to check whether this logging happens. The rough logic is as follows:
feature{
scenario{
Given()
// set up the call
When()
// make a FakeRequest via reverse routing - logging will done in a separate thread via a Future
Then()
Thread.sleep(50) // sleep to allow logging to finish
// check if the logging has been done
The issue is the Thread.sleep. I have added that call in to block the main testing thread in order to give enough time to elapse for the Future which does the logging in a separate thread to complete before actually doing the checks to see if the logging has been done.
My question is whether there is a better way to do this? In reality if my application is running and the logging is taking an inordinate amount of time, then the main thread which governs the application will not terminate until the Future that does the logging in a separate thread finishes. So I don't see a problem of putting in the Thread call above to simulate that. But I just want to confirm if this is correct.
For me, there is absolutely no other way than to do this. If I try to replicate how the app behaves in reality with my test, then the main thread for the test should complete and terminate even though the future for the logging is still going on; there is no call back in the test and neither should there be.
Assuming you're using ScalaTest ; you can use whenReady construct ; which periodically inspects the passed future, until it is either ready or the configured timeout has been surpassed;
see
http://www.artima.com/docs-scalatest-2.0.M5/org/scalatest/concurrent/Futures.html
http://doc.scalatest.org/2.0/index.html#org.scalatest.concurrent.ScalaFutures
Related
In Flutter if I create a Timer, will the supplied callback get executed if the application is in background?
I think documentation is not clear on this or I might have missed it (please supply a link if you find it anywhere).
I just tried doing this with a timer set up to 10 seconds and it works fine.
I assume that is approach is not very reliable and other methods* should be used instead. I think if the app is paused/terminated by operating system to preserve battery or due to low memory, nothing will be executed. But for me this situation could be an ok approach.
* I know there are isolates so I guess I could spawn the timer inside one of these. Downside is that the isolate must be regular function (or static method) so no access to application data in my scenario. Then there are different scheduling packages etc but I'm trying to avoid these for now. I know about background tasks but I'm really looking for an answer on code execution using timers.
I found Apple's document to understand why i should use run loop to implement task in main dispatch queue.
According to Apple docs,
The main dispatch queue is a globally available serial queue that executes tasks on the application’s main thread. This queue works with the application’s run loop (if one is present) to interleave the execution of queued tasks with the execution of other event sources attached to the run loop. Because it runs on your application’s main thread, the main queue is often used as a key synchronization point for an application.
but still, i can't understand 'why' run loop is needed. it sounds like 'it needs run loop because it needs run loop'. I will very appreciate it if someone explain me about this. Thank you.
why i should use run loop to implement task in main dispatch queue
Normally, you don’t, because you are already using one!
In an application project, there is a main queue run loop already. For example, an iOS app project is actually nothing but one gigantic call to UIApplicationMain, which provides a run loop.
That is how it is able to sit there waiting for the user to do something. The run loop is, uh, running. And looping.
But in, say, a Mac command line tool, there is no automatic run loop. It runs its main function and exits immediately. If you needed it not to do that, you would supply a run loop.
DispatchQueue.main.async is when you have code
running on a background queue and you need a specific block of code to
be executed on the main queue.
In your code, viewDidLoad is already running on the main queue so
there is little reason to use DispatchQueue.main.async.
But isn't necessarily wrong to use it. But it does change the order of
execution.
async closure is queued up to run after the current runloop completes.
i can't understand 'why' run loop is needed
Generally, a run loop is not needed for command line apps. You can use run loops if you have a special need for one (e.g. you have some dynamic UI that is performing some tasks while you wait for user input), but the vast majority of command line apps don’t require run loops.
As the docs say:
A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.
So, if you need to have your app wait for some incoming events or you’re dispatching tasks asynchronously between queues, then, fine, employ run loops, but otherwise, don’t bother. Most command line apps don’t need to use run loops at all.
I just started learning about Play framework lately and really like it so far.
There is just one thing that isn't clear to me. I'm a Java developer, with an blocking
and multi-threaded way of thinking so async programming is a little new to me.
So, Play framework uses an asynchronous WS API which doesn't block thread that calls it, nor
it blocks or spawns any other thread. When doing some async programming usually you have
to spawn a new thread and then make a WS call so you don't block your main thread. So my question here is how does Play's WS API manages to do async call to a web service without blocking current thread and without spawning a new one? Does it fire a request and then the main thread every once in a little checks if there is a Response available in the Future object? I'm aware of how to use it but I want to know what's the deal "under the hood". How would it be implemented in Scala? A simple example if possible would be a nice help.
Thanks in advance and best regards!
Under the hood play uses async-http-client which is based on NIO. A request will be dispatched and when the server responds, a callback (in this case the completion of the future) will be executed on a thread from the threadpool. This way no thread has to be blocked.
Play uses an "execution context", which is typically a thread pool, as described in the documentation:
It’s important to understand which thread code runs on with futures.
In the two code blocks above, there is an import on Plays default
execution context. This is an implicit parameter that gets passed to
all methods on the future API that accept callbacks. The execution
context will often be equivalent to a thread pool, though not
necessarily.
So no new threads are spawned, but only because there is already a pool of threads available for such work.
Let's say that if I read from www.example.com/number, I get a random number. In my iPhone app, I want to be able to continuously read from that address and display the new number on the screen after each request is finished. Let's also assume that I want this process to start as soon as the view loads. Lastly, as a side-note, I'm using ASIHTTPRequest to simplify the web requests.
Approach 1: In my viewDidLoad method I could synchronously read from the URL in a loop (execution will not continue until I get a response from the HTTP request). Pros: the requests are serial and I have full control to respond to each one. Cons: the UI never gets updated because I never exit the function and give control back to the run time loop. Clearly, this is not a good solution.
Approach 2: In my viewDidLoad method I create a timer which calls a fetchURL function once per second. Pros: each request is in a separate thread, and the UI updates after each request is finished. Cons: the requests are in separate threads, and cannot be controlled well. For example, if there is a connection timeout on the first request, I want to be able to display an error popup, and not have any further requests happen until settings are changed. However, with this approach, if it takes 3 seconds to timeout, two additional requests will have already been started in that time. If I just slow down the timer, then data comes in too slowly when the connection is working well.
It seems like there should be some approach which would merge the benefits of the first two approaches I mentioned. I would like a way that I could decide whether on not to send the next request based on the result of the previous request.
Approach 3: I considered using a timer which fires more quickly (say every .25 seconds), but have the timer's function check a flag to see what to do next. So, if the previous request has finished, it sends a new request (unless there was an error). Otherwise, if the previous request has not finished, the timer's function returns without sending a new request. By firing this timer more quickly, you would get better response time, but the flag would let me get the synchronization I wanted.
It seems like Approach 3 would do what I want, but it also seems a little forced. Does anyone have a suggestion for a better approach to this, or is something like Approach 3 the best way to do it?
You could do this using GCD with less code and using fewer resources. This is how you could do it:
In viewDidLoad call a block asynchronously (using dispatch_async) that does the following:
Load the data with a synchronous call and handle timeouts if it failed.
If successful, inform the main thread to update the UI.
Queue a new block to run after a delay that does the same thing (using dispatch_after).
To call back to the main thread from another thread I can think of these methods:
If you want to update a custom view, you can set setNeedsDisplay from your block
Otherwise, you could queue a block on what's called "main queue", which is a queue running on the main thread. You get this queue by calling dispatch_get_main_queue. and then treat it like any other queue (for example you can add your block by calling dispatch_async).
If you don't want to use blocks you can use the NSObject's performSelectorOnMainThread:withObject:waitUntilDone: method.
See GCD Reference for more details.
That said, you should never keep performing small requests so frequently (unless for specific tasks like fetching game data or something). It will severely reduce battery life by keeping antenna from sleeping.
I believe an NSOperation is what you need. Use the number 1 solution above, but place the code in your NSOperation's main method. Something like this:
The .h file
#interface MyRandomNumberFetcher : NSOperation {
}
#end
The .m file
#implementation MyRandomNumberFetcher
- (void) main {
// This is where you start the web service calls.
}
#end
I'd also recommend adding a reference to the UI controller so your operation queue class can call it back when it's appropriate.
Here's another suggestion. Create an NSOperationQueue that will run your requests on a different thread. If you find you need to refresh the UI call performSelectorOnMainThread. When the request completes create another request and add it to the queue. Set the queue to run only one action at a time.
This way you'll never have two requests running at the same time.
I am trying to post some data before my application terminates. Iam doing this by genrateing sockets using CFStreamCreatePairWithSocketToCFHost and later on I have the callbacks for reading and writing.
But I am not able to post any data. It goes through all the functions but doesnot enter into callbacks. Does that make sense to anyone?. Is there anyway to get this working?
Thanks,
Sowri
Yes, after applicationWillTerminate is called, there are no more iterations of the run loop. Since CFSocket and CFStream both use the run loop to manage the sockets and to provide data via the callback, this will not work. Also, it's very important to note that the application may be restricted from doing certain things at this stage and that if your application does not terminate, the operating system will terminate the application. It may be a better idea to write a small log to a database and then post that information back the next time the application starts.
My gut feeling is that after the applicationWillTerminate method is done, it will just stop the whole app, without giving any other run loop the chance to execute, let alone do callbacks. So my guess is that calling asynchronous methods in the applicationWillTerminate won't even start. You're just too late at that point to start networking.
The applicationWillTerminate: callback is not the place to do any kind of critical operation because as the name implies, your application will terminate and it won't wait for your code to finish doing something.
What are you trying to post; if you explain why you want to do this we may be able to offer a better solution.