Android: which thread is native method running in? - android

Is there any sense in calling a native function from a separate Java thread, or is it already being run in a separate thread by Dalvik VM?

Native methods are run just like other methods(unless specified otherwise in method description). You should handle the cases where you need to to run code that is slow so that UI wont be blocked. There are multiple ways for this, check this:
http://developer.android.com/resources/articles/painless-threading.html

Related

Access to UI thread for callbacks from Java library?

I am trying to implement an Android app as cleanly as possible.
To this end, I have defined a Java library for doing my logic and non-Android specific functionality.
For example, my app does a lot of network calls to REST apis and generates models and validation.
The library is using Retrofit and it handles asynchronous calls. However, now I need to chain calls and this means either:
Callback from first call triggers next request (potentially leading to 'callback hell').
Entering on the UI thread by default, create a new thread to do the requests, but then I need to be able to join the UI thread again when returning to the caller.
I'm not keen on (1) as we already have code like this and its a mess.
(2) would be my preferred option if there was a way to get a reference to the incoming thread (UI thread), then be able to join it again when the models are ready to be returned.
Is this possible?
To run anything on a thread you need some kind of a message loop. The UI thread is a part of Android and I guess it's impossible to run something on it without access to Android classes.
It's easy to get the UI thread using system API. Then you can post runnables to be run on that thread.
new Handler(Looper.getMainLooper()).post(new Runnable(){
public void run(){
// your code
}
});
You could use an AsyncTask to accomplish this. An AsyncTask is, as the name suggests, an asynchronous class that has both a doInBackground method, which executes in the background similar to a Thread, and a onPostExecute method, which runs on the UI and allows you to perform any UI-related activities. More information on AsyncTask may be found here: http://developer.android.com/reference/android/os/AsyncTask.html

libDispatch serving main queue without dispatch_main on 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.

How to cancel a task that has native code (C/C++)?

Background
I have a short yet heavy task that uses NDK (JNI) in order to do some bitmap manipulation.
On some cases, I need to cancel the task and go to other things.
However, since the task uses a lot of memory too, and in the end also creates a large bitmap, this could cause out-of-memory errors.
The question
How should I cancel a task that has native code in it? Is there a best practice for this?
Maybe some kind of interrupted exception that I can use for C/C++, so that as soon as it is caught, I can at least free all of the memory?
Maybe I should add some kind of listener (observer) to the native code? Or maybe I should call a method that I need to assume the caller has?
The simplest way?
Spin the task on a thread. You may spin the thread in Java and call into JNI from there. It's easier than pthreads.
Introduce a volatile flag (boolean variable), set it to false on task startup.
In the task, check the stop flag as often as it's practical. If true, abandon the task (you might throw an exception to return through several levels of function nesting, but you don't have to).
When you want to cancel, set the flag from the main thread. Wait for the task to notice that.
This won't work well if the slowest part of the task is calling a library/OS function - that function won't check for the flag.
There's no safe builtin mechanism in C++ for correctly terminating a thread of code that does not want to be terminated (maybe signals, but they kill the whole process, not a thread). Periodically checking for the flag is what I mean by "wanting to be terminated".
I've seen this approach used before, and I think the best approach would be to create a isCancelled() method that you can call periodically from your native code in order to determine when to stop. If you're using AsyncTask, that method should already exist.

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)

does a java function call spawns new thread for its execution?

Suppose i have one simple function in my program. Whenever i call that function does a new thread or process is spawned to execute the function or it is executed under the main thread memory space only. Please help... any pointers will be appreciated.
Thanks in advance,
Rupesh
When you call a method in Java it will run within the same thread of execution as the code that called it. Unless you explicitly create a new thread within the body of the method.
When you call a method, processing just moves into that method. This is a general rule across pretty much every language.
As Dave Johnston said, no - unless you explicitly create a new Thread.
Of course, you can get new threads turning up if the method you call creates new threads as part of how it works.
There's a difference between threads and processes. Threads are Java's solution to multi-tasking (and a good solution it is too). A process is an operating system thing. Depending on your JVM, a new thread may or may not run in a new process.
Either way, all threads within a JVM access the same memory space. Slightly paranoid note: there are some synchronisation issues within JVM memory to do with CPU-level memory caches - see the documentation about the volatile keyword if you're doing serious multithreaded coding.
You can have multiple JVMs running with separate memory, e.g. if you run separate commands from the command line.
Called function is executed in the same thread.
Advice: you should start learning programming from C. Then the underhood functioning of Java (or anything else) won't confuse you.

Categories

Resources