recipe № 027

Calling class methods from multiple threads

Calling method of a class (in multithread application) is possible, but you have to pay attention to the way you do it. Typically, situation in thread based code will be very similar to what you can see below.

There are few things you have to consider here. First of all, JVM can have only one, active, thread. It means that each thread running in parallel must acquire access to JVM by attaching to it. You can find description here. Especially, make sure to pay attention to following section:

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.

In general, what we want to do, is to create JVM and pass it to all threads. Inside thread’s function, each thread can access JVM by acquiring access to it:

Of course, we need to create JVM instance before we access it. We can do it following way:

And we need to spawn threads as well:

You can download full example, illustrating execution of JVM based code inside C, here: recipeNo027.

References:

  1. J.S. Gray, Komunikacja między procesami w Unixie, ARKANA 1997
  2. Java Native Interface Specification: The Invocation API – link
  3. B. Nichols, PThreads Programming – link