libDispatch serving main queue without dispatch_main on Android - android

I am using libDispatch (GCD) opensource on Android platform.
So, most of the complex time consuming tasks are being done through NDK (where i am using libDispatch).
For some calls, I am using dispatch_async(get_main_queue)...This is where the problem is coming...
I am able to run tasks in the concurrent queues but not on main queue.
Since this requires dispatch_main() to be called which we cannot do on here as Java thread will be blocked in that case.
So, is it possible to run the Java UI on some secondary thread and hook the dispatch_main() to serve the dispatch_main_queue here?
OR : Do I need to keep serving the main_queue from JAva main UI thread through JNI ?

Look into _dispatch_main_queue_callback_4CF which is the function you can call to drain the main queue. It will return like a normal sensible function after executing the queued operations, instead of killing the thread like dispatch_main.
Note that you'll need to call _dispatch_main_queue_callback_4CF on a regular basis from your Java UI thread, possibly each iteration. The official Cocoa implementation uses _dispatch_queue_wakeup_main() which uses mach messages to kick the main thread out of any sleep states so it can guarantee the callback function is called quickly, but you'd have to do some work to enable that and build your own libDispatch port. In reality on Android I don't think the main UI thread is ever put to sleep while your app is active so it shouldn't be an issue.
There is a ticket open on the libDispatch site at https://libdispatch.macosforge.org/trac/ticket/38 to make _dispatch_main_queue_callback_4CF a public function. The ticket is marked "Accepted" but no word on if/when that will happen.

Related

What is the need of main thread in Android?

i know that the android app runs in the main thread means UI thread.I want to know what is need of main thread to run an app? What happens if we do not use the main thread to run app.Why main thread is necessary?
Well it needs a thread. Every app ever written has at least one- even the simplest Hello World app in the simplest language. A thread is just a series of instructions being run on the processor. So even if your app doesn't multithread at all, the one series of instructions it is running would be a thread- you could even call it the main thread if you wanted. So it would literally be impossible to have no main thread at all.
What makes the main thread special in Android is that you're only allowed to change visible elements on it. If Android didn't have that restriction, you'd have the possibility of race conditions and inconsistent UIs- the possibility that views are being changed on one thread while another is drawing to the screen. To prevent this you'd need to do a lot of manual locking. Instead, Android decided to only allow these changes on the main thread. That prevents a large class of timing bugs and race conditions (although not all, depending on how you implement your models).
From this link:
What is the need of main thread?
When an Android application is first started, the runtime system creates a single thread in which all application components will run by default. This thread is generally referred to as the main thread. The primary role of the main thread is to handle the user interface in terms of event handling and interaction with views in the user interface. Any additional components that are started within the application will, by default, also run on the main thread.
Why is main thread necessary?
Any component within an application that performs a time-consuming task using the main thread will cause the entire application to appear to lock up until the task is completed. This will typically result in the operating system displaying an “Application is unresponsive” warning to the user. Clearly, this is far from the desired behavior for any application. In such a situation, this can be avoided simply by launching the task to be performed in a separate thread, allowing the main thread to continue unhindered with other tasks.
Please refer to the link to understand more about main thread with an example.
For more details, you can follow this link.

Synchronization between worker threads of an ExecutorService

Does the fact that an ExecutorService stores tasks in a blocking queue create a happens-before relationship between the completion of one task and the subsequent start of another task?
My reason for asking is that I've been tasked with writing a Cordova plugin for Android. Cordova plugins have a method called execute(...) that is overridden to perform different actions. Apparently, the plugin is instantiated once, and then execute(...) is called repeatedly in a worker thread of an ExecutorService. If my understanding of how Cordova plugins work is correct, then I wonder if I have to synchronize execute(...)'s access to the plugin state.
Edit: My understanding of how Cordova plugins work was incorrect, so my reason for asking this question has been invalidated. But I'll leave it up out of curiosity. (Cordova plugins are constructed, and execute(...) is called, in a thread named JavaBridge... apparently always the same thread, though this is not documented.)
No, the tasks being stored in a BlockingQueue does not guarantee thread safe execution of the worker threads. The ExecutorService interface and it's implementation provide a framework that abstracts the creation of individual threads. The number of worker threads spawned by the executor depends on the pool size configured.
Once a worker thread is spawned, it goes about doing it's work normally. If it gains access and tries to modify an object that is currently being modified by another worker thread, then undefined behavior will happen. It is left up to you to ensure that the modification happens in a synchronized manner. An example of this can be found in the PhotoManager.java class in the sample app available at http://developer.android.com/training/multiple-threads/index.html (intended as a multi threading example for Android developers).
The BlockingQueue is a queue that holds the tasks. The term 'Blocking' refers to the manner in which elements are inserted and removed from the queue. As such, it does not provide any guarantees about the actions taken by the tasks that it holds.

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)

Why is a single threaded model used to update the UI as main thread?

The Qt doc says,
As mentioned, each program has one thread when it is started. This
thread is called the "main thread" (also known as the "GUI thread" in
Qt applications). The Qt GUI must run in this thread.
The Android doc says,
Like activities and the other components, services run in the main
thread of the application process
And iOS,
It is strongly recommended not to update UI controls etc from a
background thread (e.g. a timer, comms etc). This can be the cause of
crashes which are sometimes very hard to identify. Instead use these
to force code to be executed on the UI thread (which is always the
“main” thread).
Why does they use a single threaded model to update UI ?
The short answer is, it's the only reasonable way to ensure that the display is not corrupted.
The long answer is that allowing multiple threads to update the UI results in deadlocks, race conditions, and all sorts of trouble. This was the painful lesson taught by Java's AWT (among other UI systems) that allows multiple threads to touch the UI. See, for instance, Multithreaded toolkits: A failed dream?. That post refers (via dead links) to Why Threads Are A Bad Idea and Threadaches.
iOS and Android force you to work with UI only from main thread. The reason is the same as a shared object, thread safe[About]... in multithread environment
Android example error
FATAL EXCEPTION: Thread-19449
E/AndroidRuntime: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views
iOS example error
This application is modifying the autolayout engine from a background thread" error?

Separate Threads for UI and Logic - Android

I want to create separate threads for implementing the core logic and updating the GUI.
Both threads should not share data with them directly. For this, i want to create a vector queue with synchronized get() and put() methods.
Suppose if an onClick event happens in the GUI thread, it notifies the core thread that it received the OnClick event. So the core thread implements something and puts the result in the vector. At this point, the GUI thread is notified of the received result and it fetches it and updates the screen.
I cant figure out how to do this. Is there a way this could be implemented?
You can do that as you would in any other framework or environment. The Android api offers you a lot of high level ways of handling multithreaded applications like you described (AsyncTask, Handler/Thread/Runnable, etc), but you can also wrap these in your own processing queue. I've done that recently where I created a logical queue for processing, and when I push something to the queue, I run a method that checks my queue for items and processes them on a background thread. You can notify the system when your processing is complete by sending broadcast intents and registering IntentFilters at the Activity level (don't forget to unregister) or you can implement your own listener interfaces the way the Android UI framework does with UI events on Views
At the heart of it though, however you wrap it, AsyncTask makes it really easy to call back and forth between background threads and the main UI thread. onPreExecute, onProgressUpdated and onPostExecute all run on the UI thread and doInBackground runs in a background thread that is automatically created for you. Doesn't get any easier than that

Categories

Resources