This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Other JSE/JEE APIs and the fly likes JNI - Attach thread to a VM in an arbitrary context? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Other JSE/JEE APIs
Bookmark "JNI - Attach thread to a VM in an arbitrary context?" Watch "JNI - Attach thread to a VM in an arbitrary context?" New topic

JNI - Attach thread to a VM in an arbitrary context?

Luc Lieber

Joined: May 17, 2010
Posts: 14

It may seem like a simple question, but how would I attach a thread to a VM that was NOT created through native code? (That is, not created through the JNI_CreateJavaVM method).

My solution consists of a Java application that calls a native shared library, and I've found it necessary to spawn a new thread from within the native code and attach it to the VM.

I see all sorts of solutions around the net that all rely on having the JavaVM pointer already available, however the only JNI related item that I have available is possibly a JNIEnv pointer. While it may not seem like the 'best practice', I am desperately limited in what I can do differently at this time.


* I mean...come on, would it kill the JNI designers to store a pointer to the JavaVM in the environment contexts?

** I also assume that this answer isn't out there on the net anywhere, because this topic is one of the first hits on Google now........

I think that I figured it out now...

The solution that I'm going with is caching the JavaVM pointer when I catch it in the JNI_OnLoad method is invoked when loading the library. I thought that caching JNI related items was considered bad practice, but oh well. It seems to work.

That's how I solved it, in-case anyone else has a similar issue.
I agree. Here's the link:
subject: JNI - Attach thread to a VM in an arbitrary context?
Similar Threads
Garbage collection of native objects
How to call java method from c function??
Persistence in JNI
JNI - The data area passed to a system call is too small.
how to invoke HttpRequest from a C code?