18446744073709551615
18446744073709551615

Reputation: 16832

Android: how Java threads correspond to native threads?

In Android, if I call functions from the same JNI library from different Java threads, will the JNI functions be called on the same native thread or in different native threads?

Will the answer be the same for all Android versions?

(I suspect that AsyncTask is not the best choice if you call a JNI library that needs to be initialized and called on the same native thread.)

Upvotes: 2

Views: 1789

Answers (1)

Henry
Henry

Reputation: 43738

Regarding native code, there is no distinction between Java threads and native treads, its all just a thread. You won't change the thread by calling a native method from Java, it will execute on the same thread as the Java code before.

The Java VM holds some extra information for each thread, so threads created in native code have to be attached to the VM first.

The following sections from the JNI specification give some hints:

Creating the VM

The JNI_CreateJavaVM() function loads and initializes a Java VM and returns a pointer to the JNI interface pointer. The thread that called JNI_CreateJavaVM() is considered to be the main thread.

Attaching to the VM

The JNI interface pointer (JNIEnv) is valid only in the current thread. Should another thread need to access the Java VM, it must first call AttachCurrentThread() to attach itself to the VM and obtain a JNI interface pointer. Once attached to the VM, a native thread works just like an ordinary Java thread running inside a native method. The native thread remains attached to the VM until it calls DetachCurrentThread() to detach itself.

The attached thread should have enough stack space to perform a reasonable amount of work. The allocation of stack space per thread is operating system-specific. For example, using pthreads, the stack size can be specified in the pthread_attr_t argument to pthread_create.

Detaching from the VM

A native thread attached to the VM must call DetachCurrentThread() to detach itself before exiting. A thread cannot detach itself if there are Java methods on the call stack.

Upvotes: 1

Related Questions