I'm learning RxJava and I have some doubts regarding the Scheduler.
When to use which one. The AndroidSchedulers.mainThread() is quite easy and clear,
whenever we need to come to the Android UI thread, we can use this scheduler.
But I'm confused with the other Schedulers
Schedulers.io()
Schedulers.computation()
Schedulers.newThread()
In many samples I have seen pepople using Schedulers.io() and Schedulers.computation() for network calls ,
db operations etc. Can we pick any of them randomly for background tasks?
If not which are the suitable situations to pick each? When to use Schedulers.newThread()?
It would be helpful if someone could explain it in simple words. Thanks in advance!!
io(): When you want to perform I/O bound work like database requests, network calls etc. use io. This scheduler is backed by an unbounded thread pool(which may cause OutOfMemory error if you go crazy with number of threads you are using). What it essentially means is that you don't get the overhead of creating a new thread every time. See more Why is creating thread expensive?
newThread(): As the name implies, it will create a new thread every single time.
computation: If you have some expensive CPU bound operation, you should use this Scheduler. This scheduler is bounded i.e there a limited number of threads based on the system.
As other have pointed out, please take a look at official documentation to understand more here
Related
I'm currently learning Android programming and I'm doing my first application using VS 2017 in C# (Xamarin). Right now I'm trying to understand how to split a complex computation into several threads - more accurately, the features I should look into.
Now, what I want to do is to iterate over all possible values of an unsigned int and perform some computation on it. It's a search, so some of those numbers will be of interest and I need the threads to update a progress bar and some view containing any results found so far. The complexity here is the huge number of operations that will be performed.
I've looked into Async Tasks, Thread Pool Executor, Thread Factory, Blocking Queues and Runnables. So I'm thinking a Thread Pool sounds like the way to go, especially by specifying how many processors are available and how many threads can be used.
Going by this SO question/answer, I would use an Async Task for a short operation and Java threads for more complex operations. So, despite using C# Xamarin, I guess I'm looking into Javal.Util.Concurrent.Thread's..
My goal with all this, is to allow the user to start this complex task and pause it at any point, or abort, as well as save the search state at any point to resume later. To do this, I want to subdivide this search on all possible uint values into multiple tasks - perhaps thousands of small tasks that could be executed by worker threads. For the pause feature, I was thinking the example in Android's documentation, that I previously linked, which implements Pause/Resume methods in a custom Thread Pool Executor. The save/store should be easy.. if my tasks are ordered all I need is to keep track of the last value tested and fruitful values.
I've setup a custom Thread Pool Executor, Factory and Runnables. However, I am quite confused as to how to do two things:
How exactly should I add runnables to the queue? And from which thread?
How, and where, do I know when the search was completed? What happens to the minimum number of threads in the Thread Pool Executor when the job is completed? I want to destroy all the threads when it's over.
In my operations I could have thousands of tasks. In fact, I can decide between 4096 large tasks, or 65536 smaller tasks. They can be identified by a range of uints to be checked, or a single uint index. But either way I know ahead of time how many they are and I think it would be more efficient if I didn't have to create that many runnables... Is there a way I can customize how the threads will pick up their next work from the Queue?
Or perhaps the Thread Pool Executor is just not the right tool for what I'm trying to achieve here?
I'm mostly looking for some insight on the multithreading tools available in Android and how can I go about implementing a proper solution for my problem.
You should definitely have a look to reactive programming http://reactivex.io/ and https://github.com/ReactiveX/RxJava
This is the best and cleanest way to execute tasks in background, for example you could do :
myObservable
.subscribeOn( Schedulers.io() ) // Thread where you execute your code
.observeOn( AndroidSchedulers.mainThread()) / Thread where you get result
.subscribe(...)
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.
What are the benefits to use Schedulers.newThread() vs Schedulers.io() in Retrofit network request. I have seen many examples that use io(), but I want to understand why.
Example situation:
observable.onErrorResumeNext(refreshTokenAndRetry(observable))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())...
vs
observable.onErrorResumeNext(refreshTokenAndRetry(observable))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())...
One of the reasons i have seen is -
newThread() creates a new thread for each unit of work. io() will use a thread pool
But what is the influence of that argument on the app? And what other aspects there are?
You are correct that the benefit of using Schedulers.io() lies in the fact that it uses a thread pool, whereas Schedulers.newThread() does not.
The primary reason that you should consider using thread pools is that they maintain a number of pre-created threads that are idle and waiting for work. This means that when you have work to be done, you don't need to go through the overhead of creating a thread. Once your work is done, that thread can also be re-used for future work instead of constantly creating and destroying threads.
Threads can be expensive to create, so minimizing the number of threads that you are creating on the fly is generally good.
For more information on thread pools, I recommend:
What is the use of a Thread pool in Java?
What is a thread pool?
Thread pool pattern (Wikipedia)
I have a http server which is gonna be really busy, there are few HttpHandlers inside it which all of them start their job with a new Thread() , since i still can not compeletely understand ThreadPoolExecutor's Usage (When you should use, when no need to), i really could use a little tip about it and do i need to use one?
Plus is there any roof for the threadPoolExecutor's max Threads ?
Same goes for the android, i dont understand why should i use ThreadPoolExecutor instead simply use newThread()?
Basically ThreadPoolExecutor is just a high level API from java to do task in multiple thread without dealing with low level API (Creating thread manually)
For a little example a ExecutorService executor = Executors.newFixedThreadPool(5); will run the tasks you submit in 8 threads.
You can try to understand it more by reading this documentation.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
and this tutorial
http://tutorials.jenkov.com/java-util-concurrent/threadpoolexecutor.html
you must use ThreadPoolExecutor when you do not know how many times your new Thread() will be called because you have limited resources if you let unlimited call to new Thread() you will get in trouble like out of memory exception. in restricted world like android it is necessary to know how many times you create thread and if it is not in control of you for example your user input determines the creation of thread you must use ThreadPoolExecutor.
Creating and destroying threads has a high CPU usage, so when you need
to perform lots of small, simple tasks concurrently the overhead of
creating your own threads can take up a significant portion of the CPU
cycles and severely affect the final response time. This is especially
true in stress conditions where executing multiple threads can push
CPU to 100% and most of the time would be wasted in context switching
(swapping threads in and out of the processor along with their
memory).
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)