Design problem: coalescing objects sent to a Handler - android

I'm looking for advice or critique of a design concept for coalescing Runnable objects posted to a Handler. The case is that I have a background thread that generates small chunks of work that must be done on the event thread. Each chunk is posted to a Handler as a Runnable in the usual way. It turns out that if one of these Runnables has not started executing, it would be easy to modify it to do additional work when it does run instead of constructing and posting another Runnable. This coalescing of work chunks would be both cheaper than constructing another Runnable and would also cut down on the problem of the background thread flooding the event queue.
There are a couple of problems, though. First, I need to have access to the last Runnable delivered to the event queue. As far as I know, neither Handler nor Looper offer any such function, so I was planning to just keep a reference to the last posted Runnable in my background thread code. I'm just assuming that maintaining a reference like this isn't going to cause problems anywhere in the system.
The more serious issue is that I'd have to have some way of knowing if a Runnable has been taken off the queue and started. I plan to handle that by adding a flag to my Runnable class and setting at the start of the run() method. There would still be some synchronizing necessary to avoid race conditions between testing the flag and updating the Runnable (background thread) and setting the flag once the Runnable starts executing (event thread).
Has anyone done anything like this, and if so, how did you do it? Am I overlooking something that I need to deal with?

That seems like a way to code some nasty bugs.
I have a program, that receives feed veeeeery often and posts it on multiple components, and it actually doesn't do much harm and doesn't have any visible side effects.
If you really want to go with it (I might not fully understand your situation), wouldn't it be easier, to have some "work chunks" pool, where all the needed work will be stored and some kind of work starter that will launch a new Runnable once in a while.
It goes like this:
With the first event, the "work starter" posts a runnable to a handler. This runnable asks the pool to give him all the work currently available and processes it, at the end it tells the "work starter" that it has finished, starter runs another runnable, that asks the pool for a new work, etc...
The runnable you post can be a subclass of your own worker runnable, to make those queries to the pool and report about finished work easier. No need to store flags, or change runnables. And no need to deal with concurrency problems (if you have only 1 handler that is)

Related

Looper or while in a thread?

I'm trying to understand the Looper...
This time i'm getting a little bit confused, because I've only used (until now) the while(true) condition to maintain the thread in an infinite loop.
I just want to know if it is better to use the Looper or the while(true) condition.
I've searched a possible answer to my question in internet and I was quite disappointed in finding codes that use Looper and while(true) together.
Probably I didn't get the point of using the Looper but, you know, we are here to learn... isn't it?
Looper is a mechanism that keeps thread open to process Messages that are sent to it via Handler. In that sense, they are similar to while(true) in that the Thread stays open forever (or in this case until you explicitly tell it to close). However, unlike while(true), you can send the Messages to it from another thread. Every time you create a Handler, it binds itself to the Looper thread that it was created in. Then, every time you post a message to that Handler, it processes that message on the thread in which it was created.
The most common, well-known Looper thread in Android is the main UI thread. This thread is always running. It runs code that are posted to it. Most commonly drawing operations, but if you take a view and call View#post, it will run the code in the next draw cycle. This is because all View objects have a Handler that was built on the main UI Looper thread.
The UI Looper can actually be referenced to Looper.getMainLooper() method, and you can create a Handler that posts messages to this thread like so: new Handler(Looper.getMainLooper());.
Though if you need, you could create your own Looper thread that acts as a parallel thread to the UI thread. You can't do drawing operations on it, but you could use it as a worker thread for other operations. That way you don't have the overhead of creating a new thread every time you need to do something intensive.
I just want to know if it is better to use the Looper or the while(true) condition.
I'd say, as a general rule, unless you need some very specific low-level control, use the API that are provided by the framework, whichever the framework is.
They usually take care of many aspects that would otherwise have you implement them yourself, such as messaging, task deletion, and so on...
I guess that with the while (true) loop you are trying to achieve some regular task repetition.
In this particular case, yes, use a Handler with its own Looper, so the UI Thread is not blocked, and post your Runnable instances regularly with postDelay(Runnable, long).
#DeeV 's answer already gives you a good understanding about the mentioned components, but you sure will find out everything you need in Android documentation.

Understanding when and why to use different Android threads

Hopefully someone can explain this to me or point me to a resource I can read to learn more. I am building an app that uses a ListView and a custom list adapter that I modeled off one of the many tutorials available online such as this one:
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
It worked fine. However, every example of how to do this runs the process of building the list of objects to be displayed and collecting the required data on separate threads.
I want to know why/couldn't you just put everything into onCreate? I can't see a reason why you would need separate threads to make this happen. Is there some general form/standard for when/what must me run on certain threads?
The Android docs on this are very good, as with most things.
The upshot is: the UI should always be responsive. So if you have some operation that will take enough time that the user will notice, you might want to consider not running it in the UI thread. Some common examples are network IO and database accesses. It's something of a case-by-case basis though, so you have to make the call for yourself a bit.
Well, if building the list of objects is not a relatively short process, doing it in onCreate() would be blocking/slowing the main thread. If you use a separate thread, it will allow the android os to load all of the UI elements while you are waiting for the list to be populated. Then when the list of objects is ready, you can instantly populate the already initialized UI, as opposed to waiting to initialize the UI until after the list of objects is built. It ensures that your application will always be responsive for the user.
Because you only have 0.5 sec to execute onCreate — after which the dreaded ADN (application not responding) error message is displayed. So unless your list view is super simple you won't make it it in time. And even if your list view is super simple it is better to learn it the proper way.
BTW: I don't even use threads, I use one or more Services to do all the work. Even more difficult to implement but more robust and responsive as well.
The reason you don't do things in onCreate or on the UI thread is for responsiveness. If your app takes too long to process, the user gets shown an App Not Responding dialog.
my teacher once said: every software can be written in a single (big) for loop.
And if you think: it can be... maybe at NDK level.
Some SDK developers wanted to make the software developers tasks easier and that's, why exists the SDK's and frameworks.
Unless you don't need anything from multitasking you should use single threading.
Sometimes there are time limitations, sometimes UI/background/networking limitations and need to do stuff in diff threads.
If you see source code of Asyntask and Handler, you will see their code purely in Java. (of course, there some exceptions, but that is not an important point).
Why does it mean ? It means no magic in Asyntask or Handler. They just make your job easier as a developer.
For example: If ProgramA calls methodA(), methodA() would run in a different thread with ProgramA.You can easily test by:
Thread t = Thread.currentThread();
int id = t.getId();
And why you should use new thread ? You can google for it. Many many reasons.
So, what is the difference ?
AsyncTask and Handler are written in Java (internally use a Thread), so everything you can do with Handler or AsyncTask, you can achieve using a Thread too.
What Handler and AsyncTask really help you with?
The most obvious reason is communication between caller thread and worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task.A Caller Thread may not be the UI Thread always). And, of course, you can communicate between two thread by other ways, but there are many disadvantages, for eg: Main thread isn't thread-safe (in most of time), in other words, DANGEROUS.
That is why you should use Handler and AsyncTask. They do most of the work for you, you just need to know what methods to override.
Difference Handler and AsyncTask: Use AsyncTask when Caller thread is a UI Thread. This is what android document says:
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers
I want to emphasize on two points:
1) Easy use of the UI thread (so, use when caller thread is UI Thread).
2) No need to manipulate handlers. (means: You can use Handler instead of AsyncTask, but AsyncTask is an easier option).
There are many things in this post I haven't said yet, for example: what is UI Thread, of why it easier. You must know some method behind each kind and use it, you will completely understand why..
#: when you read Android document, you will see:
Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue
They may seem strange at first.Just understand that, each thread has each message queue. (like a To do List), and thread will take each message and do it until message queue emty. (Ah, maybe like you finish your work and go to bed). So, when Handler communicates, it just gives a message to caller thread and it will wait to process. (sophiscate ? but you just know that, Handler can communicate with caller thread in safe-way)

Android and threads

I have 2 questions in terms of android development and threads
1) When do you think I should use threads in android development?
2) If I have the main UI thread waiting on some variable to be set before it displays a toast, then I thought about having a while(true) loop in a sperate thread that keeps checking that variable. Now if the variable is set, how do I call the method on the first thread (The UI thread) that will display a toast
Thank you so much
Using threads directly is not necessary in most cases. The android facilities for threaded programming are great, and easy to use.
You have about three options to call the UI thread from another thread:
Handler - set an handler on the other thread from the UI thread, and send it a message when need.
AsyncTask - Perform the main task in background, but modify the UI before, during and after completion.
PerformOnUiThread - call this method with a runnable to modify the UI on the UI thread.
Good article to read about is Painless Threading.
Never have a while(true) loop that continuously runs. It'll burn massive amounts of resources and, in your case, accomplish very little.
Threads are good to run for (mainly) background tasks and resource intensive tasks (so that you don't block the UI thread). To create a new Thread, use the following:
new Thread(new Runnable(){
public void run(){
//do stuff here.
}
}
).start();
You can also look into the Android AsyncTask to avoid using Threads directly.
Depending on the type of app you are working on/with, proper use of Theads can be key to having a fast and responsive UI.
Key Rule:
If you need to to anything that accesses the filesystem, network, image loading, or anything that requires more than simple value or state checks, immediately launch and perform that effort in a thread. As already stated here, a number of options are available, although myself I usually use:
change_UI_if_needed_to_indicate_click_response();
new Thread(new Runnable(){
do stuff here ;
}).start()
You can also use standard (non-inline) thread objects like this.
That may be bad practice, I don't know. Anyway, it works well for me, and isn't really the point of your question.
If you want to run something on the UI thread using standard Java, instead of specialized Android object that specifically allows for such things, there is a post(Runnable) method attached to each and every view. For me, that's the easiest my to get code back onto the UI thread.
myView.post(new Runnable{
codeForUI();
});
My general rule is to try to never run anything on the UI thread that does not need to be there. Hope that helps.
You must use thread, if you want to prevent application from the current error or crash "Application not responding".
i use it when i call web services, geolocations.
Good frensh article:
http://souissihaythem.blogspot.com/2011/08/application-not-responding.html
http://souissihaythem.blogspot.com/2011/08/application-not-responding-solution.html

Android - Question on postDelayed and Threads

I have a question about postDelayed. The android docs say that it adds the runnable to the queue and it runs in the UI thread. What does this mean?
So, for example, the same thread I use to create my layout is used to run the Runnable?
What if I want it as an independent thread that executes while I am creating my layout and defining my activity?
Thanks
Chris
Yes that would run on the UI thread.
If you want to run a background thread then do it the normal way.
Thread t = new Thread(new Runnable(){});
t.start()
But if you want to change the UI at all in response to something that a background thread might do, then you can use postDelayed().
Any changes to the UI must be done on the main UI thread.
Congratulations! You found one of the places where there is more than one solution.
Handlers, and PostDelayed can be nice lightweight ways of having your foreground activity called on a regular basis. Even the messages are reused. These are used in the Snake example program (Snake/SnakeView.java/sleep()) to make the snake move. It runs as 'post a message delayed by 500ms', in 500ms catch it in HandleMessage (the default for Handlers), move, then send it again. Even the message is reused with obtainMessage(). I've used these for making a button update while it is pushed down.
Threads are a bit heavier. You might use these for background or where you are already used to running a thread. Make a 'new Thread(aRunnable).start()'. I haven't used them much on the Android.
Launch an Intent with StartActivityForResult() and catch the result with OnActivityResult to make a standard RPC. See step 2 of the notepad example for more information.
Look into more Intents to launch for different scenarios. I find putting your 'create and launch intent' into separate functions helps maintenance and debugging.
Good luck!

Handler vs AsyncTask

I'm confused as to when one would choose AsyncTask over a Handler. Say I have some code I want to run every n seconds which will update the UI. Why would I choose one over the other?
IMO, AsyncTask was written to provide a convenient, easy-to-use way to achieve background processing in Android apps, without worrying too much about the low-level details(threads, message loops etc). It provides callback methods that help to schedule tasks and also to easily update the UI whenever required.
However, it is important to note that when using AsyncTask, a developer is submitting to its limitations, which resulted because of the design decisions that the author of the class took. For e.g. I recently found out that there is a limit to the number of jobs that can be scheduled using AsyncTasks.
Handler is more transparent of the two and probably gives you more freedom; so if you want more control on things you would choose Handler otherwise AsynTask will work just fine.
My rule of thumb would be:
If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.
If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.
Always try to avoid using AsyncTask when possible mainly for the following reasons:
AsyncTask is not guaranteed to run since there is a ThreadPool base and max size set by the system and if you create too much asynctask they will eventually be destroyed
AsyncTask can be automatically terminated, even when running, depending on the activity lifecycle and you have no control over it
AsyncTask methods running on the UI Thread, like onPostExecute, could be executed when the Activity it is referring to, is not visible anymore, or is possibly in a different layout state, like after an orientation change.
In conclusion you shouldn't use the UIThread-linked methods of AsyncTask, which is its main advantage!!! Moreover you should only do non critical work on doInBackground.
Read this thread for more insights on this problems:
Is AsyncTask really conceptually flawed or am I just missing something?
To conclude try to prefer using IntentServices, HandlerThread or ThreadPoolExecutor instead of AsyncTask when any of the above cited problems ma be a concern for you. Sure it will require more work but your application will be safer.
If you want to do a calculation every x seconds, you should probably schedule a Runnable on a Handler (with postDelayed()) and that Runnable should start in the current UI thread. If you want to start it in another thread, use HandlerThread.
AsyncTask is easier to use for us but no better than handler.
The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.
AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
The answer is that both can be used to update the UI from background threads, the difference would be in your execution scenario. You may consider using handler it you want to post delayed messages or send messages to the MessageQueue in a specific order.
You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.
AsyncTask presumes you will do something on the UI thread, after some background work is finished. Also, you can execute it only once (after this, its status is FINISHED and you'll get an exception trying to execute it once more). Also, the flexibility of using it is not much. Yes, you can use THREAD_POOL_EXECUTOR for a parallel execution, but the effort might be not worthy.
Handler doesn't presume anything, except handling Runnables and Messages. Also, it can be run as many times as you wish. You are free to decide to which thread it must be attached to, how it communicates with other handlers, maybe produce them with HandlerThread. So, it's much more flexible and suitable for some repeated work.
Check different kind of Handler examples here.
They are best interview question which is asked.
AsyncTask - They are used to offload of UI thread and do tasks in background.
Handlers - Android dosent have direct way of communication between UI and background thread. Handlers must be used to send message or runnable through the message queue.
So AsyncTasks are used where tasks are needed to be executed in background and Handlers are used for communication between a UI and Background Thread.
doInBackground - basically does work in another thread.
onPostExecute - posts the results on the UI thread and it is internally sending message to handler of main thread. Main UI thread already has a looper and handler associated with it.
So basically,if you have to do some background task,use AsyncTask. But ultimately,if something needs to be updated on UI,it will be using main thread's handler.

Categories

Resources