while learning the difference between multi-threading and Concurrency.i follow this stackoverflow answer
according to my understanding AsyncTask is just used to on or off the use of main thread{ui thread} while events like http request or fetching data from database. and after task is done main thead is reallocated to the event by AsyncTask task.
but Android Official says "An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread"
now i am confused.
android use multi-theading its just wrapper class for thread management.
C# async and await is diffrent concept.
An AsyncTask "touches" two threads: Main/UI and the Background one. There are few of its methods that run on Main/UI Thread (onPre/onPostExecute()) and one method that is run on a WorkerThread in background. There is an internal sync/queue between those methods.
Concurrency (async/await) doesn't (necessarily) use a second thread but uses "moments of when the CPU is free". Think about this non-real case: if the Main/UI Thread is 100% busy then no any Concurrency could be executed until the Main/UIThread has a bit of "free CPU cycles" to share. Intead, in this last example AsyncTasks will do its job asynchronously without take in count other Threads (and its results will be queued to UI/MainThread to be processed later).
Related
I am trying to figure out which threads should do what in Android.
The only thing I have found stated in the official documentation is that camera.open() should be put into its own thread.
What about:
camera.startPreview()
camera.stopPreview()
camera.release()
It doesn't state which thread they need. Must they be run on the main thread (ui thread)? Or am I free to choose?
Why am I trying to figure this out? camera.startPreview() when run on the main thread is causing my app to jitter/lag for a short period of time, this heavily affects my application as it is put inside a viewPager and I do not wish to have the camera to always preview (which would cause no lag, but takes up system resources).
Any ideas?
The documentation for Camera states that the class is not thread safe and should not be called from multiple threads at once (I suppose, unless you are performing your own synchronization).
It says that the callbacks will be delivered to the thread that makes the call to open
From the reference (emphasis mine):
This class is not thread-safe, and is meant for use from one event thread. Most long-running operations (preview, focus, photo capture, etc) happen asynchronously and invoke callbacks as necessary. Callbacks will be invoked on the event thread open(int) was called from. This class's methods must never be called from multiple threads at once.
From the open(int) method reference:
Callbacks from other methods are delivered to the event loop of the thread which called open(). If this thread has no event loop, then callbacks are delivered to the main application event loop. If there is no main application event loop, callbacks are not delivered.
Caution: On some devices, this method may take a long time to complete. It is best to call this method from a worker thread (possibly using AsyncTask) to avoid blocking the main application UI thread.
The thread it needs is the one you use to call open(int).
So to answer your question, yes you are relatively free to choose, but you must remain consistent.
Why use Looper/Handler when I could use an Executor method(s)?
The Looper/Handler duo seems rather clunky and doesn't seem to do a great deal beyond allowing the queuing of runnables and seemingly has less flexibility.
What was the looper design rationale?
Thanks.
A looper by itself does not have many advantages over an executor. It is how Android manages worker. But you are able to get the main thread of your app with Looper.getMainLooper(), this can have the following advantages:
You can change the ui from the MainLooper, (only do if not a compute intense background task, since you would freeze the UI)
Execute Runnables "in-sync" with the all the other native tasks. Meaning you post your Runnable in the same queue as android does
No need to create a thread yourself. You can use the already running Looper.
I am little bit confused with multithreading in Android. I am aware we can achieve using AsyncTask and Handler. Generally when should we implement by extending Thread Class in Android? Can anyone give an example that we need to do it only by extending thread class but not with AsyncTask or Handler.
Consider a example app, we have a bouncing ball in an activity(forget the animation part), I need to change the color of the ball every 20 minutes, and I need to get the color code from the server and update the ball UI. Now how can I achieve this ? Can someone explain using AsyncTask or Handler and also only using Thread Class(without Asynctask or Handler)?
How should I handle downloading large payloads from server using services.
Thread
Long task in general
Invoke by thread.start() method
Triggered from any thread
Runs on its own thread
Manual thread management/code may become difficult to read
AsyncTask
Small task having to communicate with main thread
Invoke by execute() method
Triggered from main thread
Runs on worker thread
Must be executed and created from the main Thread
Service
Task with no UI,but should not use for long Task. Use Thread within service for long Task
Invoke by onStartService()
Triggered from any Thread
Runs On Main Thread
May block main(UI) thread
IntentService
Long task usually no communication with main thread if communication is needed then it is done by Handler or broadcast
Invoke via Intent
Triggered from Main Thread (Intent is received on main Thread and worker thread is spawned)
Runs on separate thread
Can't run task in parallel and multiple intents are Queued on the same worker thread.
Thread: Use it to separate long running computation from Main Thread ( UI Thread). If you don't need to update UI or send messages back to UI Thread, use it for long running tasks. But you don't really need to extend Thread and write your logic by overriding Thread methods. But still HandlerThread is effective compared to java Thread.
AsyncTask : it is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few milli seconds at the most). Recommended for 5 milli seconds task execution.
Service: Use it to handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
HandlerThread/Handler: A HandlerThread is effectively a long-running thread that grabs work from a queue, and operates on it. You can use it even to send results back to UI Thread via Handler of UI Thread.
Have a look at below posts for more details:
Asynctask vs Thread vs Services vs Loader
Handler vs AsyncTask vs Thread
Creating Background Service in Android
Android: Toast in a thread
An AsyncTask is basically a thread. It has 3 callBack methods(main) and the are executed in this order top to bottom:
1. onPreExecute()
2. doInBackground()
3. onPostExecute()
4. onProgressUpdate()
The onPreExecute() and onPostExecute() are running on the UI thread and doInBackground() is a separate thread as such. If you spawn a thread(not a AsyncTask), and try to set a property of a UI element from it, this will raise an exception saying: the original thread(the UI thread) which created the view can only modify it. So only the UI thread has these two properties:
Only it can add/modify the UI of the App
It cannot be blocked for more than 5 secs(ANR exception)
So to over come both these limitations in one go, we have AsyncTask, it can run resource consuming operations(network access, implementing gaming logic etc) in doInBackground(), and still provide ability to alter the UI from onPreExecute() and onPreExecute().
I think title itself says what the my question is...
AFAIK, in Java, when work of a Thread is completed i.e. run() method has completed executing, Thread itself will finish and dies.
So, When my Activity(I mean UI) is idle for a long time, what the UI thread will do? does it sleeps? or does it do any other work?
Thanks to all...
I believe the question is not really about Java threads in general, but about the Android "main thread" (also called the "UI thread").
To quote from the JavaDoc for the Android Handler:
When a process is created for your application, its main thread is
dedicated to running a message queue that takes care of managing the
top-level application objects (activities, broadcast receivers, etc)
and any windows they create. You can create your own threads, and
communicate back with the main application thread through a Handler.
This is done by calling the same post or sendMessage methods as
before, but from your new thread. The given Runnable or Message will
then be scheduled in the Handler's message queue and processed when
appropriate.
In other words: The main thread is responsible for dequeuing messages/runnables from a queue and processing them. That main thread is blocked while the queue is empty (since there is nothing for it to do). If you use a Handler that was created in the main thread, that Handler's messages and runnables will actually be added to the same queue used by the main thread. Normally, the main thread will run as long as the process does.
Note: An Android app can actually have multiple processes, and each one will have its own main thread. However, most Android apps will only have one process (and therefore one main thread).
So I have a long running process that I want to encapsulate as a Runnable and dispatch it in a thread. To be more specific, I have a POST web service that creates a file in the file system but the creation of the file can take a very long time.
In the resource method of my web service, I want to be able to dispatch a thread to do the file creation and return the status 200. I don't think I can just do Thread.join because this would mean that the current thread would have to wait for the file creation thread to finish. Instead, I want to join the file creation thread to the main thread. Question is, how do I get the main thread in java?
I am not sure whether I get you right. Here is what I understood:
You want to preform a possibly long running operation (file creation)
you do not want you service method to block while that task is exectued
you want the task executed in a thread that exists outside the boundary/lifetime of the single request.
Am I right so far?
If sou really recommend you look into the newer concepts in java.util.concurrent. The concepts described there should give you enogh information tackkle this
Basic credo: Don't think in threads, think in tasks.
General Book recommendation: Java Concurrency in Practice by Brian Goetz
You will need to process the request asynchronously. A separate thread will be created for doing the heavy work and the request receiving thread will be free to process other requests. Please checkout following articles.
Asynchronous processing in Servlet 3.0
Asynchronous support in Servlet 3.0 spec
Asynchronous Support in Servlet 3.0
When you spawn the file-creation thread, you need to pass it some kind of reference to the parent thread, so it can communicate back (i.e. you provide something to enable a callback).
This could be the actual Thread object (obtained using Thread.currentThread, as someone said in a comment) or some other object that you use to signal when the file-creation thread is done.