• Post Reply Bookmark Topic Watch Topic
  • New Topic

JNI: Any way to tell if I am on a Java thread?  RSS feed

 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In my JNI application, my JNI code sometimes gets called from some C code that it not Java-aware. Sometimes, the thread that this is running on is completely separate from the JVM. Other times, that thread initially started in the JVM, then called some method that went native.

My JNI code needs a JNIEnv. It can get this from AttachCurrentThread(), no problem. AttachCurrentThread() is happy to be called on a thread that is already in the JVM, but doesn't tell you if this was the case, I believe.

When the JNI code has finished, it should ideally DetachCurrentThread() only if the calling thread was one of those completely separate from the JVM (before I attached it). If it was a thread started by the JVM, it should definitely not detach.

Can this be achieved? I can't see a way of telling whence the thread came.
[ March 05, 2007: Message edited by: Peter Chase ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And the answer is...

The GetEnv() function in the JNI will return a JNIEnv if the thread is already attached to the JVM, or NULL if it isn't. So, you can then go on to AttachCurrentThread() only if necessary, and you can record whether you had to attach, so you can later decide whether to detach.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!