As I understood, Firebase Database performs all the reading tasks on a single thread.
Is there a way to split that work into few different threads?
Is there a way to make a tasks execute before another? some parallel to handler.postAtFrontOfQueue() ?
The Firebase client handles all network and disk I/O on a separate thread to avoid interfering with the UI of your Android app. The callbacks into your code are invoked on the main thread, so that your code can interact with the UI.
The operations are executed in the same order in which you call their APIs. There is no way to re-order operations. There is also no way to set up multiple threads, nor have I ever seen a need for that. Interacting with a remote service is inherently an I/O intensive operations, which is not helped by multi-threading.
This sounds like a XY problem. If you describe the actual problem that you're trying to solve, we may be able to help better.
Related
The documentation for Android's SQLite interfaces mention that database accesses should be performed from an IntentService as they are potentially long-running operations, so the GUI thread should not block on them.
The IntentService is shut down as soon as no further Intents are queued for it, which would happen basically after every request, so the database handles are built up and destroyed for each query as well, which seems wasteful.
Is there a way to keep an IntentService around longer, or somehow otherwise avoid a race between the GUI thread posting more Intents and the service answering them?
Should I just make my query Intents contain a list of queries that should all be performed, or would that cause other problems with message sizes?
The documentation for Android's SQLite interfaces mention that database accesses should be performed from an IntentService as they are potentially long-running operations, so the GUI thread should not block on them.
I/O of all forms should be performed on background threads, so as not to block the main application thread. IntentService itself is not a great choice, given changes on Android 8.0+.
A more typical approach nowadays is to have database access be managed by a singleton repository (whether a manually-created singleton or a singleton supplied to you via a dependency injection framework). The repository can use any number of approaches to provide a reactive API while doing the I/O on a background thread, including:
RxJava
LiveData and ordinary threads, executors, etc.
Kotlin coroutines
If you use Room as your database access layer, it gives you all three of those options "for free". Some other ORMs offer similar capabilities.
Is there a way to keep an IntentService around longer, or somehow otherwise avoid a race between the GUI thread posting more Intents and the service answering them?
Background services can only run for one minute. If your concern is the overhead in opening the database, use a singleton repository, and only open it once per process invocation. It's also entirely possible that you do not need a service; if you have a foreground UI, a service may be pointless.
Should I just make my query Intents contain a list of queries that should all be performed...?
Um, possibly, but again, using a service here may not be necessary and definitely makes the problem more complex.
So: use a background thread for I/O. That does not have to involve a service.
Hi guys I have a question about Asyntask which is used in android studio :
As far as I know AynTask is used for user interface via one thread, the so called UI Thread. If you perform a long running operation directly on the UI Thread, for example downloading a file from the internet, the user interface of your application will “freeze” until the corresponding task is finished.
But let's say that I want to register an account so that I can login, that shouldnt take time at all so why should I use Asyntask for this?
Let's say I want to send 100 strings to the Database, that can be done in milisecs I think, so again, why to use and how to decide when to use Asyntask?
I hope you guys can help me out, I have been searching for a long time !
If you don't know how much time operation will take, you should perform it in a separate thread and then pass the results to UI thread. I think the database should be accessed in a separate thread as well as HTTP requests. In the case of time-consuming query, it may be a long operation. AsyncTask is one way to do it. You can also use other techniques. The popular technique used nowadays is applying RxJava library, which gives you the high-level functional reactive interface for writing multi-threaded applications with a few additional features. You can perform an operation in e.g. Sechdulers.io() (I/O) thread and then pass the result to AndroidSchedulers.mainThread(), which is UI thread.
There are also other techniques like using Looper & Handler from Android SDK or using Thread class from Java, but such techniques require more knowledge, more work, writing more boilerplate code & you have more problems to deal with.
I have looked through many examples/tutorials of using SQLite in Android. Let's say you have an app that uses SQLite, ContentProvider, CursorLoader, a custom CursorAdapter.
Now all major examples of this that I've found rely on a CursorLoader to fetch data to the CursorAdapter, which by the nature of CursorLoader happens in an Async - UI thread safe manner. However, these same examples all make insert/delete/update calls through the ContentResolver on the main thread (e.g. from onClick, onResume, onPause). (Example) They don't wrap these calls in an AsyncTask or launch a separate thread or use the AsyncQueryHandler.
Why is this, how can so many well written blogs/examples make such an obvious mistake? Or are simple single row insert/delete/update calls so quick that they are safe enough to launch from the Main/UI thread? What is the proper way to do these quick calls?
I also got confused about the samples making calls on the main thread. I guess the samples just simplified the demonstrations avoiding extra threads and callbacks, since single insert/update/delete call may return quickly.
Besides the Loader pattern for query, android did provide a helper class AsyncQueryHandler, since API level 1, for async CRUD operations with full CRUD callbacks supported. The AsyncQueryHandler works inside with a HandlerThread for the async operations and delivers the results back to the main thread.
So I do believe the ContentProvider queries should run in worker threads other than the UI, and those samples may not be best practices according to the official design.
=== edit
Found an annotation from the official framework docs, see this or this, Line 255:
In practice, this should be done in an asynchronous thread instead of
on the main thread. For more discussion, see Loaders. If you are not
just reading data but modifying it, see {#link android.content.AsyncQueryHandler}.
=== edit 2
Link to actual android dev guide containing the above quote
This question has been on my mind since a long time. I guess, this depends on the complexity of the file we are trying to Insert, Update or Delete. If our application is going to Insert or Update large files, it would be always right to do it asynchronously and if the files aren't going to be that big, running it on UI thread can be done.
However, it is always recommended to continue with Database operations on a separate thread.
I think you've answered your own question. I do believe CursorLoader extends AsyncTaskLoader. Calls made from UI thread only process the call TO the CusorLoader (which uses AsyncTask.) What is being done BY the call still does not occur on UI Thread. Making a call to a method/function that then runs things on a seperate thread is still doing work away from UI thread.
What work do you think is happening on the UI thread?
Please show Debug log if possible or example where you think work is done on UI.
It shouldn't be.
Not trying to argue just want to know how you've come to the conclusion of UI work?
I'm currently writing and android app, and I was using HttpClients and those classes. I spent 2 hours trying to fix some errors until I read a post that said that you cant do that operation in the main thread. So they suggested I use AsyncTask.
So My question is, how do I know which operations should be done in a different Thread? is there a list where I can read them?
Any information would be good, thanks in advance.
A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.
Some examples of other operations that ICS and HoneyComb won't allow you to perform on the UI thread are:
Opening a Socket connection (i.e. new Socket()).
HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
Attempting to connect to a remote MySQL database.
Downloading a file (i.e. Downloader.downloadFile()).
If you are attempting to perform any of these operations on the UI thread, you must wrap them in a worker thread. The easiest way to do this is to use of an AsyncTask, which allows you to perform asynchronous work on your user interface. An AsyncTask will perform the blocking operations in a worker thread and will publish the results on the UI thread, without requiring you to handle threads and/or handlers yourself.
The network exception is the only exception that will be thrown in android by blocking the UI-Thread. So you have to keep 3 rules in mind by programming in android.
Don't let the UI-Thread handle operations that will take more then 5 seconds to complete.
Don't let a broadcast receiver handle operations that will take more then 20 seconds to complete the onReceive ().
And don't handle network operations in the UI-Thread.
As other answers have said, Android is not thread safe, meaning:
You cannot manipulate the UI from a Background thread
You cannot do heavy tasks on the UI thread
Other operations of this sort could include processing large amounts of data/ database manipulation/HTTP requests/Network management. Really, I believe anything that doesn't require the UI thread but does involve large processing time should be moved to a seperate thread.
This makes logical sense, because if you were to do heavy processing, the user would feel a lag and User Experience would be compromised (and, ofcourse, could definitely be used to overload the system,etc.) Therefore, the system will kill the process and throw an error post-honeycomb.
As a result, you want to use an Async Task.
An Async Task really just opens a new Thread on which you can execute heavy processing or Network Connections. For Network Connections, I recommend the use of AsyncClients like this one that implement AsyncTask in an easier format for you to use. There are also libraries like UniversalImageLoader that will allow you to load Images into Grids/Lists.
I also highly reccomend you read the official Android documentation discussing this and there is a useful post on the Android blog about this as well. Lastly, I feel as if this post might be useful to you because it may include the error you encountered (Error because you performed the operation on the UI thread).
Other Resources I've found:
CommonsWare's Service
This StackOverflow Question has some good solutions.
In conclusion, here is an example of an AsyncTask being used. (nicely put answer from #Graham Smith).
Anything that takes a lot of time should be done in another thread. This includes large IO and network access. However I think only network access will throw an exception, anything else would cause an unresponsive UI. Although if you take way too long you'll trip a watchdog timer and the app will be killed.
As Gabe mentioned, you should do heavy tasks in separate threads.
there are two important things about android threads.
1 is the common threads..(the thread that do what you ask)
2 is the ui thread...(the thread that listens the user inreaction and draws ui)
you can change ui(Views act) only by ui thread.
on the other hand after honeycomb it is forbidden to do http requests in main thread.
(it is called strict mode)
in short, any operation that blocks user interaction should be done in another thread.
i hope this helps you.
In my app, I have to call a method which does some heavy work (I can feel device lagging). To avoid this I created an AsyncTask and it works perfectly fine.
I implemented the same thing using a Thread and here, too, it does not give any hiccup and works fine.
Now my question is which one better performance-wise - AsyncTask or Thread.
I know AsyncTask uses a threadpool to perform background tasks but in my case it will be called only once. So I don't think it will create any problems.
Can someone throw some light on it. Which one should I use for better performance?
Note: Both are being called in my Activity e.g. from UI the thread.
Can someone throw some light on it. Which one should I use for better
performance?
I think if you imagine case when you start once native Thread and AsyncTask i think that performance won't differ.
Usually native threads are used in the case if you don't want to inform potential USER with relevant information about progress in some task via UI. Here, native threads fail because they are not synchronized with UI thread and you cannot perform manipulating with UI from them.
On the other hand, AsyncTask combines background work with UI work and offers methods which are synchronized with UI and allow performing UI updates whenever you want via invoking proper methods of its lifecycle.
Generally if some task lasts more than 5 seconds you should inform USER that
"something working on the background, please wait until it will be finished"
For sure, this can be reached with both in different ways but this strongly depends on character of your task - if you need to show progress of task(how much MB is already downloaded, copying number of files and show name of each in progress dialog etc.) or you don't(creating some big data structure in "silent" only with start and end message for instance).
So and at the end of my asnwer:
Which one should I use for better performance?
Completely right answer i think you cannot get because each developer has different experiences, different coding style. How i mentioned, their performance not differ. I think that it's same(if you will read 50 MB file, it won't be faster read neither native thread nor AsyncTask). It depends again on character of task and your personal choice.
Update:
For tasks that can last much longer periods of time, you can try to think also about API tools provided by java.util.concurrent package(ThreadPoolExecutor, FutureTask etc.)
Async tasks are also threads. But they have some utility methods that make it very easy to small background tasks and get back to the UI to make changes to it. The performance would depend on your specific use case. Making absolute statements as to which one is always better would be simplistic and meaningless.
Note that the main advantage of Async tasks over threads is that Async tasks provide helper methods such as onPreExecute(), doInBackground(), onProgressUpdate() and onPostExecute() which make it very easy to perform short background tasks while also interacting with the UI (such as updating a progress bar). These kinds of methods are not available in generic Threads. Basically, Async tasks are threads with UI interaction component built in. Yes, you can use workarounds to try and update the UI from regular threads as well but Async tasks have been specifically built for this purpose and you don't have to deal with Context leaks and so on if you follow it's abstractions.
Async tasks are created to make developers' lives easier.
To sum up:
Async tasks are also threads
Async tasks make it easy to interact with UI while doing short background tasks
Neither is inherently more efficient. It depends on what you want to do.
Good rule of thumb: Use Async tasks if you need to get back to/update the UI after you are done with your background task. Use a regular thread if you don't.
The most common use of Thread are short-term tasks because they need a lot of power and tend to drain the battery and heat the phone up.
And the common use of AsyncTasks are lengthy tasks because of the same battery drain.
But a Thread is far more powerfull, because an AsyncTasks internally uses a Thread itself, but you don't have to configure that much.
ASYNC TASK and Thread do the same thing,
The difference is that you have more control on bare thread and you can benefit from the power of CPU in terms of complex implementation, the velocity of performance depends on your approach on how you implement the threading.
Depending on this article I can say that asynchronous multithreading is the fastest way to perform complex tasks.
https://blog.devgenius.io/multi-threading-vs-asynchronous-programming-what-is-the-difference-3ebfe1179a5
Regarding showing updates to user on UI thread, you can do that by posting on UI from the background thread (check UIhandler and View.Post)