I have an Android app that has separate things going on but are all basically threads (and definitely are threads to the Android debugger)
There are multiple animation listeners that loop and call each other
There is a countdown timer that is always counting down to zero after it is initiated
Now I need to consider adding more countdown timers. How many of these kind of looping processes can I have going on? In this particular implementation I am not concerned about performance, efficiency, etc, until it becomes apparent.
Insight appreciated
I would be very surprised to learn that you exhausted the number of threads you can use safely in an android application, as long as you are properly managing their lifetime and prevent "busy loops"and the like from occuring.
One thing I did learn though, I am pretty sure you can only have 5 asynctasks operational at any time, and they will arbitrarily continue to exist and get killed or respawned by themselves if you start new ones...ie if i turned an asynctask on then off five times the debugger will say 5 async threads operational, but I can continually toggle on and off as much as I want because the resource pool will kill the oldest dead asynctask.
There is no maximum that I know of. I can tell you, however, that you most likely don't NEED that many threads.
You can keep countdown listeners in a single thread using Android's Handler, specifically the postDelayed() method. Start a Looper in a separate thread, and use a Handler to manage the timeouts -- don't busy wait, or sleep-loop.
I don't believe countdown timer will create threads--it should simply add your task to a queue on your main thread from the looks of it.
All your listeners should take place on the same thread as well (there is a single thread that manages all listeners (for visible objects anyway).
So you probably aren't using anywhere near as many threads as you think you are. If you were creating a lot of threads I'd be worried--they are really hard to keep synchronized and may cost you a lot more than you'd gain, but with the structures listed I'd go ahead and allocate as many as you feel appropriate (but test for performance on a cheap device of course)
Related
I'm new in Android and multithreading programming and I read in the Android.developers docs that:
It is not recommended to manipulate a view from an other thread than
the UIThread.
Ok I accepted the rule but now I would like understand why? Anyone have a simple example for me to understand why?
Thanks in advance for your help
As was stated in the comments, to avoid race conditions is part of it. Its also just a bit of bad practice. UI Thread should handle UI issues, that's what its there for. Other threads should handle other issues, that's what they're there for.
Consider the situation of having a class that modifies a TextView based on some remote query. For this you should use something like AsyncTask which allows callbacks to the UI Thread.
Now if there is ever and instance where multiple threads are working on the same UI component, what may happen is that the "wrong" (unintended) one finishes first. This is a race condition.
Also, good programming encourages a separation of concerns. You don't have the manager working on the painting that the artist is working on, so why would we imitate this behavior in software?
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
A thread should be used in a long running process that would block
the UI from updating. If it's more than a second or two you
might want to put it into a background thread and notify the user
with a dialog or spinner or something. If you lock the UI thread for
more than 5 seconds the user will be prompted with a kill or wait
option by the OS.
I have been working on an Android application that uses Google maps and then runs some lengthy network intensive operations in the background. Currently, I am using a thread to run them on and they take anywhere from 30 seconds to 7 minutes to finish. After watching a few courses on Pluralsight about AsyncTasks and Background services, I now know that threads should ideally not be used for anything taking more than a few seconds. I am now altering my solution to run live with GPS rather than taking several minutes to perform the operations. The goal is to update an array every OnLocationChanged event.
I am having trouble in thinking about how I could alter a global array every OnLocationChanged event while also accessing it from the UI main thread. What is my best option for accomplishing this? Would I be able to use a process or AsynTask to accomplish this or would I need to go client/server route? Where would the OnLocationChanged be called?
First off, onLocationUpdated is called on the UI thread. So you don't have to worry about multithreading there.
Secondly- if you have a variable that needs to be touched by two threads you just use a semaphore and take it before you need to access it on each thread, and release it when done. Make sure to keep that block of code as small and quick as possible. There's more advanced stuff you can do for high performance needs, but that's good enough for 99% of code.
Thirdly- as I mentioned in my comment, your understanding of threading is wrong. The UI thread should not be used for more than is needed. AsyncTasks should not run for more than a few seconds (as there's a single thread they run on by default, so running long would block other requests). But a Thread can run as long as it needs to, and should be used if it needs long term background processing.
Looking at the source code of the Volley library, I'm curious of how exactly does the "cleanup" of the dispatcher threads work. A RequestQueue contains one CacheDispatcher instance and an array of NetworkDispatcher instances. Both of these dispatcher classes extend Thread and are started as soon as they are created. After that, they run in an infinite loop until their quit() methods are called.
My question is, how are those threads actually stopped (i.e. what, if anything, prevents them from running indefinitely until the system kills the app), for example when the user leaves the application. The quit() methods of the dispatchers is called only from the RequestQueues stop() method, but that method itself isn't called from anywhere in the Volley, aside from the start() method to cleanup the possible previous dispatchers before initializing the new ones.
What I am sort of aiming at with the question is how much of an issue are the idle threads, and how they behave when the task (i.e. a group of activities) goes from the foreground to the background and hangs around for a while. Androids task switcher can hold quite a bit of apps (altough some of them might have been ejected/stopped), and most of them presumably use libs like volley/okhttp/picasso which have their thread pools. In theory that could add up to quite a lot of threads (albeit idle).
I understand this is a fairly low-level question and would probably require a lot of theory to explain correctly, if someone can provide a satisfactory answer touching on the bold stuff above, I'd be happy to accept it.
So over the last few months I've created a fairly complex game that's near ready for release. The only problem left is that it is running as smoothly as I would hope and I think this is because of the way I have structured my threads. Right everything in my code is done through a surfaceview. All calculations, position updates, drawing, collisions, etc are done there. I was wondering if I am supposed to put all updates into one thread then handle only drawing in the surfacethread. Is this the proper way to do it, if so how would i implement that(asynctask,thread,handler,etc)?
Sure, you should avoid doing any time-consuming calculation in the UI Thread. You could also incur in an ANR error message.
You can either use:
AsyncTask, but be aware that it has some flaws and drawbacks. For example it isn't guaranteed to even start or complete.
IntentServices or HandlerThreads if you need to do operations that need to be executed sequentially in a worker thread
WorkerThreadPool if you need to execute true parallel tasks.
Good morning everyone,
I am sending data to a device from android each 40ms. Up until now, I have been using a while(true) thread and thread.sleep because I didn't know better :). Now I see I have a lot of "better" options like:
TimerTask
Asynctask
ScheduledThreadPoolExecutor
Which is the best one for my scenario? Keep in mind that there may be an exception thrown if the device disconnects so I will need to stop sending values until the connection is restored. Furthermore, the data must be sent at pretty precise intervals and it should, in no case, be sent less than 40ms before the previous one.
Thanks!
Plenty of options, however, just prior to that AsyncTask does not really belong to that list. Asynctask is simply used to perform an operation in a background thread outside of the main UI thread and not really used for scheduling repeating tasks.
For repeating tasks, the options are:
Android: execute code in regular intervals
Use a countdowntimer as the countdowntimer executes in the main thread (if that is what you want)
Or use a TimerTask.
My suggestion for your case is option 1 or 3.
-V